ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
struct Base {
    virtual Base* clone() const { cout << "Base::clone "; return new Base(*this); }
};
struct Derived : Base {
    Derived* clone() const override { cout << "Derived::clone "; return new Derived(*this); }
};
int main() {
    Base *p = new Derived();
    Base *q = p->clone();
}
  1. A. Base::clone
  2. B. Derived::clone
  3. C. Compile-time error: Derived::clone's return type must exactly match Base::clone's
  4. D. Compile-time error: clone() cannot be both virtual and return a pointer

Correct answer: B. Derived::clone

Derived* is a covariant return type: a subtype of Base*, which C++ explicitly permits for an overriding virtual function. Derived::clone genuinely overrides Base::clone, and the virtual call via p dispatches to it, printing Derived::clone.

More OOP with C++ and Java questions

Exams that ask this topic