Assuming standard headers and using namespace std, what does this C++ code print? struct B { B() { cout << “B”; } ~B() { cout << “~B”; } }; struct D : B { D() { cout << “D”; } ~D() { cout << “~D”; } }; int main() { D d; }
Correct answer C. BD~D~B
Explanation
When a derived object is created, its base class subobject is constructed first, so B prints before D. Destruction runs in the exact reverse order: the derived destructor body runs first (~D), then the base destructor (~B). This guarantees the derived part can still use the base part throughout its own lifetime.
Answer checked How we write and check questions
Discussion