Doubt on virtual destructors

Hello All
I have been reading Effective C++ by Scott Meyers. The book says that the destructor of a base class should be defined as virtual if and only if the base class has a virtual function. But consider the case below.

If the derived class has additional member variables, should not the destructor of base class be defined as virtual. Otherwise, if a pointer to the base class is pointing to a derived class object and if the user tries to delete the derived class object using the base class pointer, the derived part of the object (the additional member variables in the derived class) will not be deallocated and can lead to memory leak.

Can some one let me know what is wrong with my argument and why destructors have to be virtual only if the base class contains virtual functions?

Thank you
jai.
The book says that the destructor of a base class should be defined as virtual if and only if the base class has a virtual function


If a class has no other virtual methods, you need a pointer to the derived type to get the correct behavior for the class. If you need a pointer to the derived type, why would you be using a base class pointer to refer to the class?
closed account (o1vk4iN6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

class A
{
public:
    /*virtual*/ ~A() { std::cout << "~A()" << std::endl; }

};

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

int main()
{
    A* a = new B;
    delete a;
    return 0;
}
// without virutal

~A()

//with virtual

~B()
~A()
The reason why he says that is like cire already pointed out. If the derived class has no virtual methods than you will need to dynamic_cast in order to call a method and so only one destructor need be called.

When you dynamic cast you are automatically calling the derived class' destructor from a derived class pointer.

With polymorphism, you are calling the derived class methods from a base class and in that case, you need to also call the derived class destrcutor virtually.
Last edited on
Topic archived. No new replies allowed.