0

Maybe there is the same question but I haven't found it.

I have following code:

class MBase {
    public:
        ~MBase() { cout << "Base destructor\n" << endl; }
};

class MF: public MBase {
    public:
        ~MF() { cout << "MF Destructor" << endl; }
};

class MS: public MBase {
    public:
        ~MS() { cout << "MS Destructor" << endl;}
};

int main() {

    unique_ptr<MBase> ptr1 = unique_ptr<MF>(new MF());
    unique_ptr<MBase> ptr2 = unique_ptr<MS>(new MS());

    return 0;
}

And there is output

Base destructor

Base destructor

Isn't it right? Why derived destructors weren't called? What I have to do to fix that?

oleeq2
  • 37
  • 1
  • 8

2 Answers2

0

when using polymorphism and inheritance in C++, you should have a virtual destructor

Stephane Rolland
  • 34,892
  • 31
  • 111
  • 159
0

Polymorphism in C++ requires virtual destructor, so that it would be possible to delete an instance of derived class via a pointer to the base class object.

Long story short - allways declare destructors virtual if class is supposed to be derived from.

When to use virtual destructors?

Community
  • 1
  • 1
mr.pd
  • 1,363
  • 10
  • 21