Constructors can't be made explicitly virtual, but destructors can and must often be made virtual. 建议将类层次结构的根基类的析构函数声明为虚拟的.
Destructors in a class hierarchy will always be called. So destructors must have a function body otherwise there will be link-time error. 派生类的析构函数先被调用,完成之后,直接基类的析构函数被静态调用.
A better design alternative is to NOT declare a virtual destructor as pure. If that's the case, the pure virtual destructor must be defined by the class designer. Because every derived class destructor is internally augmented to statically invoke each of its virtual base and immediate base class destructors.
NOTE:one may both define and invoke a pure virtual function, provided it is invoked statically and not throught the virtual mechanism.
Why a destructor has to be virtual? What happens if you want to manipulate an object through a pointer to its base class (that is, manipulate the object through its generic interface)? This is certainly a major objective in object-oriented programming. The problem occurs when you want to delete a pointer of this type for an object that has been created on the heap with new.
A difference between a destructor (of course also the constructor) and other member functions is that, if a regular member function has a body at the derived class, only the version at Derived class gets executed. Whereas in case of destructors, both derived as well as base class versions get executed.
#include <>
class Base
{
public:
Base(){ cout<<"Constructor: Base" << endl;}
~Base(){ cout<<"Destructor : Base" << endl;}
};
class Derived: public Base
{ //Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived" << endl;}
~Derived(){ cout<<"Destructor : Derived" << endl;}
};
void main()
{
Base *Var = new Derived();
delete Var;
}
Try executing this code, you'll see the difference. The constructors are getting called in the proper order. But the destructor of the derived class was not called at all.
This is where the virtual mechanism comes into our rescue. By making the Base class Destructor virtual, both the destructors will be called in order.
There is one more point to be noted regarding virtual destructor. We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment