What is the output printed by the following program: Pick ONE option
Nvidia technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What is the output printed by the following program:
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "Constructor for A Called" << endl; }
~A() { cout << "Destructor for A Called" << endl; }
};
class B {
public:
B() { cout << "Constructor for B Called" << endl; }
virtual ~B() { cout << "Destructor for B Called" << endl; }
};
class C : public B {
B a;
public:
C() { cout << "Constructor for C Called" << endl; }
~C() {
cout << "Destructor for C Called" << endl;
}
};
int main() {
B* b = new C();
delete b;
}
Pick ONE option
Show answer & explanation
When new C() is executed, the base class B constructor runs first, then the member object a (of type B) is constructed, and finally the C constructor body executes. Since B's destructor is virtual and the object is deleted through a B*, the destructor call is polymorphic: ~C() runs first, followed by destruction of member a and then the base B subobject.
Step-by-step Derivation:
new C()triggers construction order: base classB→ memberB a→ derived classCbody.
Output so far:
Constructor for B Called
Constructor for B Called
Constructor for C Calleddelete bwherebisB*pointing to aCobject. Because~B()is virtual, the call dispatches to~C().Destruction order is reverse of construction:
~C()body → memberadestructor (~B()) → baseBdestructor (~B()).Final output:
Constructor for B Called
Constructor for B Called
Constructor for C Called
Destructor for C Called
Destructor for B Called
Destructor for B Called