ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Base {
    virtual Base* clone() { std::cout << "Base::clone "; return new Base(*this); }
};
struct Derived : Base {
    Derived* clone() override { std::cout << "Derived::clone "; return new Derived(*this); } // covariant return type
};
int main() {
    Base *p = new Derived();
    Base *q = p->clone();
    delete p; delete q;
}
  1. A. Base::clone
  2. B. Derived::clone
  3. C. Compilation error: return types differ, not a valid override
  4. D. Base::clone Derived::clone

Correct answer: B. Derived::clone

C++ explicitly allows a covariant return type for an override: Derived* is a pointer to a class derived from Base, so Derived::clone() legitimately overrides Base::clone() despite the differing (but covariant) return type. Calling through the Base* dispatches to Derived::clone() as usual, printing "Derived::clone".

More OOP with C++ and Java questions

Exams that ask this topic