ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Shape {
virtual ~Shape() = default;
virtual double area() const { return 0; }
};
struct Circle : Shape {
double r;
Circle(double r) : r(r) {}
double area() const override { return 3.14 * r * r; }
};
void report(const Shape &s) {
cout << s.area();
}
int main() {
Circle c(2);
const Shape &ref = c;
report(ref);
}- A. 0
- B. 12.56
- C. Compile-time error: area() is const but Circle::area modifies r
- D. Undefined behaviour: binding a const Circle reference to a non-const Shape
Correct answer: B. 12.56
Binding a reference to a base type from a derived object (not slicing, since this is a reference, not pass-by-value) preserves the object's identity and vtable. report() takes a const Shape&, and s.area() dispatches virtually to Circle::area(), computing 3.14 * 2 * 2 = 12.56.
More OOP with C++ and Java questions
- What is printed? java class Counter { private int count; public synchronized void inc() { count++; } public int get() { return count; } }…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = new…
- What is printed? java public class Main { public static void main(String[] args) { String a = new String("hi").intern(); String b = "hi"…
- What is printed? java class Box { int value; Box(int v) { value = v; } } public class Main { public static void main(String[] args) { Box…
- Which statement about overriding equals() correctly describes the contract that must hold?