Object-Oriented Programming · Question 21 · Medium

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

#include <iostream>
using namespace std;
class Base {
public:
    Base()  { cout << "B "; }
    ~Base() { cout << "~B "; }
};
class Derived : public Base {
public:
    Derived()  { cout << "D "; }
    ~Derived() { cout << "~D "; }
};
int main() {
    Derived d;
    return 0;
}
  1. D B ~B ~D
  2. B D ~B ~D
  3. D B ~D ~B
  4. B D ~D ~B
Answer and explanation

Answer: D. B D ~D ~B

Explanation: Constructors run from base to derived (B, then D). Destructors run in the reverse order when d goes out of scope (~D, then ~B).

Previous: Which OOP concept means exposing only the essential features of an object… · Next: What is the output of the following C++ program?

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