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;
}- A. Base::clone
- B. Derived::clone
- C. Compilation error: return types differ, not a valid override
- 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
- What is printed? cpp class Base { public: Base() { std::cout << "Base() "; } virtual void show() { std::cout << "Base::show"; } }; class…
- What is printed? cpp class Complex { double re, im; public: Complex(double r, double i) : re(r), im(i) {} Complex operator+(const Complex&…
- What is printed? java interface Calculator { int calculate(int a, int b); } public class Main { public static void main(String[] args) {…
- What is printed? java class Matrix { int[][] data; Matrix(int[][] d) { data = d; } Matrix add(Matrix other) { int[][] r = new…
- What is printed? java class Vehicle { private int speed; protected void setSpeed(int s) { speed = s; } int getSpeed() { return speed; } }…
- What is printed? cpp class Stack { vector<int> data; public: void push(int x) { data.pushback(x); } int pop() { int top = data.back()…