ProgrammingVery hardHCL · Tech Mahindra 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 *b = new Derived();
    Base *c = b->clone();
    delete b; delete c;
}
  1. A. Compilation error: covariant return type not allowed
  2. B. Base::clone
  3. C. Derived::clone
  4. D. Compilation error: clone() must return exactly Base*

Correct answer: C. Derived::clone

C++ explicitly allows a covariant return type: an override may return a pointer/reference to a type derived from the base's declared return type, so Derived* clone() legally overrides Base* clone(). Dispatch is virtual as usual, so b->clone() calls Derived::clone.

More OOP with C++ and Java questions

Exams that ask this topic