Object-Oriented Programming · Question 22 · Medium

What is the output of the following C++ program?

#include <iostream>
using namespace std;
class Shape {
public:
    void name()         { cout << "Shape "; }
    virtual void area() { cout << "ShapeArea "; }
    virtual ~Shape() {}
};
class Circle : public Shape {
public:
    void name()         { cout << "Circle "; }
    void area() override { cout << "CircleArea "; }
};
int main() {
    Shape* s = new Circle();
    s->name();
    s->area();
    delete s;
    return 0;
}
  1. Circle CircleArea
  2. Shape CircleArea
  3. Shape ShapeArea
  4. Circle ShapeArea
Answer and explanation

Answer: B. Shape CircleArea

Explanation: name() is not virtual, so the call is bound at compile time by the pointer's type (Shape*) and prints Shape. area() is virtual, so it is dispatched at run time to the actual object, a Circle.

Previous: What is the output of the following C++ program? · Next: What is the output of the following Python code?

Practise object-oriented programming

Try a fresh set of object-oriented programming questions with an explanation after every answer, free and without signing up: Object-Oriented Programming practice. Or sit a full placement mock test.

More object-oriented programming questions

More technical & programming practice

DBMS · SQL · Operating Systems · Computer Networks · Software Engineering · Cloud & DevOps · GenAI Basics · Pseudo-code

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge