ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Shape {
virtual double area() const { return 0; }
virtual void print() const { cout << "Area: " << area(); }
};
struct Square : Shape {
double side;
Square(double s) : side(s) {}
double area() const override { return side * side; }
};
int main() {
Shape *s = new Square(3);
s->print();
}- A. Area: 0
- B. Area: 9
- C. Compile-time error: print() cannot call area() before Square is fully built
- D. Undefined behaviour
Correct answer: B. Area: 9
By the time main calls s->print(), the Square object is already fully constructed, so this is an ordinary (not constructor-time) virtual call. print() calls area() virtually, which dispatches to Square::area(), returning 3*3 = 9, giving "Area: 9".
More OOP with C++ and Java questions
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { } class C extends B { public String…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; A::f(); } }; int…
- What is printed? java class Vehicle { int wheels() { return 4; } } class Motorcycle extends Vehicle { @Override int wheels() { return 2; }…
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…
- 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()…