ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Base {
    virtual std::string name() const { return "Base"; }
};
struct Derived : Base {
    std::string name() const override { return "Derived"; }
};
void describe(const Base& b) {
    cout << "This is a " << b.name();
}
int main() {
    Base b1;
    Derived d1;
    describe(b1);
    cout << " | ";
    describe(d1);
}
  1. A. This is a Base | This is a Derived
  2. B. This is a Base | This is a Base
  3. C. This is a Derived | This is a Derived
  4. D. Compilation error: describe cannot bind a Derived to a const Base&

Correct answer: A. This is a Base | This is a Derived

Passing by const reference never slices; describe() receives a genuine reference to whichever object was passed. b.name() dispatches virtually based on the actual bound object each time: Base's own name() for b1, Derived's override for d1.

More OOP with C++ and Java questions

Exams that ask this topic