ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base {
virtual void f() const { cout << "Base-const"; }
};
struct Derived : Base {
void f() const override { cout << "Derived-const"; }
};
int main() {
const Base *p = new Derived();
p->f();
}- A. Base-const
- B. Derived-const
- C. Compile-time error: cannot call a const virtual function through a const pointer
- D. Undefined behaviour
Correct answer: B. Derived-const
Both Base::f and Derived::f are declared const, so they have matching signatures and Derived::f genuinely overrides Base::f. A const Base* can call const member functions, and virtual dispatch still looks at the real object's vtable, so it prints Derived-const.
More OOP with C++ and Java questions
- What is printed? java class Shape { double area() { return 0; } } class Circle extends Shape { double radius; Circle(double r) { radius =…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } @Override public String toString() { return "N(" + val +…
- What is printed? java class Employee { double bonus() { return 1000; } double pay() { return 50000 + bonus(); } } class Manager extends…
- What is printed? cpp struct Base { Base() { cout << "CtorBase "; } virtual ~Base() { cout << "DtorBase "; } }; struct Derived : Base {…
- What is printed? cpp struct Shape { virtual double area() const { return 0; } virtual void print() const { cout << "Area: " << area(); }…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { } class C extends B { public String…