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.
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).
If dynamically allocated memory is not freed, it results in a memory leak and system will run out of memory.
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 ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With