ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Base {
    virtual Base& self() { cout << "Base::self "; return *this; }
};
struct Derived : Base {
    Derived& self() override { cout << "Derived::self "; return *this; }
};
int main() {
    Derived d;
    Base &r = d.self();
    r.self();
}
  1. A. Derived::self Derived::self
  2. B. Derived::self Base::self
  3. C. Base::self Derived::self
  4. D. Compile-time error: Derived::self's return type must exactly match Base::self's

Correct answer: A. Derived::self Derived::self

Derived& is a covariant return type (a reference variant, also permitted). d.self() dispatches to Derived::self, printing Derived::self and binding r to the same object (still dynamically a Derived). r.self() is still a virtual call dispatched on the real object type, so it again resolves to Derived::self, printing Derived::self a second time.

More OOP with C++ and Java questions

Exams that ask this topic