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

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

Choose one option.
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:

  1. new Derive() calls constructors in order: Base() outputs 'Constructing Base', then Derive() outputs 'Constructing Derive'.
  2. delete basePtr is a Base pointer, and Base::~Base() is not virtual.
  3. Without virtual destructors, the compiler calls the static type's destructor (Base), not the dynamic type (Derive).
  4. Only ~Base() executes, outputting 'Destroying Base'.
  5. ~Derive() never runs—this is the bug. The output is: 'Constructing Base\nConstructing Derive\nDestroying Base'