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();
}- A. Base::clone
- B. Derived::clone
- C. Compile-time error: Derived::clone's return type must exactly match Base::clone's
- 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
- What is printed? java interface Greeter { default String hello() { return "Hi"; } } class Formal implements Greeter { @Override public…
- What is printed? cpp struct Base { Base() { cout << "Base-ctor "; } ~Base() { cout << "Base-dtor "; } }; struct Derived : Base { Derived()…
- What is printed? java public class Main { static int risky() { try { return 1; } finally { return 2; } } public static void main(String[]…
- What is printed? java class MyChecked extends Exception { MyChecked(String m) { super(m); } } public class Main { static void risky()…
- Which statement about this code is correct? java class Main { static void risky() { if (Math.random() < 2) throw new…
- What is printed? java public class Main { public static void main(String[] args) { int result = compute(); System.out.println(result); }…