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;
}- A. Compilation error: covariant return type not allowed
- B. Base::clone
- C. Derived::clone
- 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
- What is printed? java interface Greeter { String greet(); } class Main { public static void main(String[] args) { Greeter g = () -> "hi…
- What is printed? cpp struct Resource { virtual ~Resource() { cout << "~Resource "; } }; struct FileResource : Resource { ~FileResource() {…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : virtual A { void f() override { cout << "B"; } }; struct C…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } public String toString() { return val + (next != null ?…
- What is printed? java class A { final String tag() { return "A"; } } class B extends A { String tag(int x) { return "B" + x; } } // in…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "1"; } }; struct D2…