Feb 1, 2005

Virtual destructor

Both constructor and copy constructor cannot be virtual. Destructor could better be virtual.
Consider two classes: Base and Derived:

class Base{

public:

Base(){cout<<"Base called."<

~Base(){ cout<<"Base deleted."<

}

class Derived:public Base{

public:

Derived(){ cout << "Derived called." <<>

~Derived() { cout << "Derived deleted." <<>

}


Now if we delete a Derived object, then we will get
Base called.
Derived called.
Base deleted.

The reason is that the Derived class uses the destructor of Base class. Therefore, we use the keyword "virtual" in front of the destructor of Base class: virtual ~Base(). We will get
Base called.
Derived called.
Derived deleted.
Base deleted.

Which is the correct result.
When a derived class has its own behavior in function foo() and foo() is existed in its base class without virtual, program will not execute foo() in derived class but in base class. If foo() is virtual, foo() of derived will be executed correctly.
Therefore, destructor should always be virtual, isn't it?


No comments: