Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual destructor: is it required when not dynamically allocated memory?

Tags:

People also ask

Do I always need a virtual destructor?

If you are not going to delete object through a pointer to its base class - then there is no need to have a virtual destructor. Just make it protected so that it won't be called accidentally: // library.

When would you not use a virtual destructor?

In short you should not have a virtual destructor if: 1. You don't have any virtual functions. 2. Do not derive from the class (mark it final in C++11, that way the compiler will tell if you try to derive from it).

What happens if dynamically allocated memory is not freed?

If dynamically allocated memory is not freed, it results in a memory leak and system will run out of memory.

What are the necessary conditions for a pure virtual destructor?

It is must to provide a function body for pure virtual destructor as derived class's destructor is called first before the base class destructor, so if we do not provide a function body, it will find out nothing to be called during object destruction and error will occur.


Do we need a virtual destructor if my classes do not allocate any memory dynamically ?

e.g.

class A
{
      private: 
      int a;
      int b;

      public:
      A();
      ~A();
};

class B: public A
{     
      private:
      int c;
      int d;

      public:
      B();
      ~B();
};

In this case do we need to mark A's destructor as virtual ?