samedi 28 mai 2022

Must I either mark the destructor of the base class as virtual function or mark it as protected function?

As per this article, which says that[emphasis mine]:

Making base class destructor virtual guarantees that the object of derived class is destructed properly, i.e., both base class and derived class destructors are called.

As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor (even if it does nothing). This way, you ensure against any surprises later.

I think even if your base class has no virtual function,you should either add a virtual destructor or mark the destructor of the base class as protected.Otherwise, you may face memory leak when trying to delete a pointer pointed to a derived instance. Am I right?

For example,here is the demo code snippet:

#include<iostream>

class Base {
public:
 Base(){};
 ~Base(){std::cout << "~Base()" << std::endl;}; 
};

class Derived : public Base {
private:
  double val;
public:
 Derived(const double& _val){};
 ~Derived(){std::cout << "~Derived()" << std::endl;}; //It would not be called
};

void do_something() {
 Base* p = new Derived{1};
 delete p;  
}

int main()
{
    do_something();
}

Here is the output of the said code snippet:

~Base()

Could anybody shed some light on this matter?

Aucun commentaire:

Enregistrer un commentaire