Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always necessary to declare destructor as virtual, if the class contains atleast a virtual function? [duplicate]

Tags:

c++

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?

like image 569
user966379 Avatar asked Dec 27 '22 06:12

user966379


1 Answers

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.

like image 56
sbi Avatar answered Feb 13 '23 04:02

sbi