23.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
23. (C++ Question) Deleting pointer to base classes
What is the output of the following code:
#include <iostream>
using namespace std;
class Base
{
public:
Base() { cout<<"Constructing Base\n"; }
~Base() { cout<<"Destroying Base\n"; }
};
class Derive: public Base
{
public:
Derive() { cout<<"Constructing Derive\n"; }
~Derive() { cout<<"Destroying Derive\n"; }
};
int main()
{
Base *basePtr = new Derive();
delete basePtr;
return 0;
}
Pick ONE OR MORE options
Show answer & explanation
Answer: A. Constructing Base
Constructing Derive
Destroying Base
When a Base* pointer to a Derive object is deleted without a virtual destructor, only the Base destructor is called. This is a classic C++ pitfall demonstrating undefined behavior with non-virtual destructors. The Derive destructor never executes, and only the Base destructor runs, leading to resource leaks in the derived class.
Step-by-step Derivation:
new Derive()calls constructors in order: Base() outputs 'Constructing Base', then Derive() outputs 'Constructing Derive'.delete basePtris a Base pointer, and Base::~Base() is not virtual.- Without virtual destructors, the compiler calls the static type's destructor (Base), not the dynamic type (Derive).
- Only ~Base() executes, outputting 'Destroying Base'.
- ~Derive() never runs—this is the bug. The output is: 'Constructing Base\nConstructing Derive\nDestroying Base'