ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
struct Shape {
virtual double area() const = 0;
void report() const { std::cout << "Area: " << area(); }
};
struct Square : Shape {
double side;
Square(double s) : side(s) {}
double area() const override { return side * side; }
};
int main() {
Square s(4);
s.report();
}- A. Compilation error: cannot call pure virtual area() from report()
- B. Area: 16
- C. Area: 0
- D. Area: 4
Correct answer: B. Area: 16
report() is a non-virtual member calling the virtual area() on *this; by the time report() runs on a fully constructed Square object, dynamic dispatch correctly resolves to Square::area() = 4*4 = 16. Pure virtual functions CAN be called polymorphically once the derived override exists and the object is fully constructed — they just can't have a body called purely through the base's own default (unless explicitly defined).
More OOP with C++ and Java questions
- What is the behavior? cpp struct Base { ~Base() { std::cout << "~Base "; } // NOT virtual }; struct Derived : Base { int data = new…
- What is printed? cpp struct A { virtual void f(int x) { std::cout << "A::f(int) " << x; } }; struct B : A { virtual void f(double x) {…
- What is printed? cpp struct Base { virtual void f() const { std::cout << "Base::f const"; } }; struct Derived : Base { void f() {…
- What is printed? cpp struct IWalk { virtual void move() = 0; }; struct ISwim { virtual void move() = 0; }; struct Duck : IWalk, ISwim {…
- What is printed? cpp struct Base { static void hello() { std::cout << "Base::hello"; } }; struct Derived : Base { static void hello() {…
- What is printed? cpp struct Base { virtual Base clone() { std::cout << "Base::clone "; return new Base(this); } }; struct Derived : Base {…