ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base { virtual void show() { cout << "Base "; } };
struct Derived : Base { void show() override { cout << "Derived "; } };
void byRef(Base& b) { b.show(); }
void byVal(Base b) { b.show(); }
int main() {
    Derived d;
    byRef(d);
    byVal(d);
}
  1. A. Derived Base
  2. B. Base Derived
  3. C. Derived Derived
  4. D. Base Base

Correct answer: A. Derived Base

A reference parameter binds to the actual Derived object, so byRef preserves polymorphism and calls Derived::show. A by-value parameter copies only the Base part (slicing), so byVal always calls Base::show no matter what was passed.

More OOP with C++ and Java questions

Exams that ask this topic