Possible Duplicate:
When to use virtual destructors?
If all the data members of a class (which has virtual function) and it's inherited class are of non pointer type (means it can not hold any dynamic memoroy), is it required to declare destructor as virtual?
Example
class base {
int x;
public:
virtual void fn(){}
};
class der: public base {
int y;
public:
void fn(){}
};
Here do we need a virtual destructor?
No, it's not always necessary. It's just a rule of thumb, and thus not always applicable.
The real rules says:
A destructor must be declared
virtual
when objects of derived classes are to be deleted through base class pointers.
Otherwise, deleting a derived class object through a base class pointer invokes undefined behavior. (The most likely outcome is that only the base class' destructor is called.)
Of course, that rule is quite a mouthful for newbies, hence the simpler rule of thumb, which is almost always right. It is very likely that you are managing dynamically created derived class objects through base class pointers in a polymorphic class hierarchy, and it is very unlikely that you do this for non-polymorphic class hierarchies.
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