OA. free
Free
Nvidia Core Computer Science Core Computer Science Medium

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

Choose one option.
Show answer & explanation
Answer: A. Constructor for B Called Constructor for B Called Constructor for C Called Destructor for C Called Destructor for B Called Destructor for B Called

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:

  1. new C() triggers construction order: base class B → member B a → derived class C body.
    Output so far:
    Constructor for B Called
    Constructor for B Called
    Constructor for C Called

  2. delete b where b is B* pointing to a C object. Because ~B() is virtual, the call dispatches to ~C().

  3. Destruction order is reverse of construction: ~C() body → member a destructor (~B()) → base B destructor (~B()).

  4. 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