ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base {
    virtual void print() const { cout << "Base"; }
    friend ostream& operator<<(ostream &os, const Base &b) { b.print(); return os; }
};
struct Derived : Base {
    void print() const override { cout << "Derived"; }
};
int main() {
    Derived d;
    Base &r = d;
    cout << r;
}
  1. A. Base
  2. B. Derived
  3. C. Compile-time error: operator<< cannot be a friend of a class with virtual functions
  4. D. Compile-time error: r must be cast to Derived& before printing

Correct answer: B. Derived

operator<<(ostream&, const Base&) is inherited by reference for any Base-compatible object; r is a reference to the real Derived object, so b.print() inside operator<< performs a virtual call that dispatches to Derived::print, printing Derived.

More OOP with C++ and Java questions

Exams that ask this topic