Possible Duplicates:
Under what circumstances is it advantageous to give an implementation of a pure virtual function?
Why do we need a pure virtual destructor in C++?
Compiler doesn't force the Child class
to implement a destructor when its Base
has pure virtual
destructor.
struct Base
{
virtual void foo () = 0;
virtual ~Base() = 0;
};
Base::~Base() {} // necessary
struct Child : Base
{
void foo() {}
//ok! no destructor needed to create objects of 'Child'
};
Funny part is that; compiler rather forces the Base
to define a destructor body. Which is understood. (Demo for reference)
Then what is the purpose of having pure virtual
destructor in Base
class ? (Is it just to disallow Base
creating objects?)
To be simple, Virtual destructor is to destruct the resources in a proper order, when you delete a base class pointer pointing to derived class object.
Q) What is purpose of Virtual destructor? To maintain the call hierarchy of destructors of base and derived classes. Destructor can be virtual so that we can override the destructor of base class in derived class.
A virtual destructor is used to free up the memory space allocated by the derived class object or instance while deleting instances of the derived class using a base class pointer object.
Pure virtual destructors in C++ To work correctly, classes with virtual methods must also have virtual destructors.
Sometimes an abstract base class has no virtual methods (= often called a “mixin”) or no methods at all (= often called a “type tag”).
To force those classes to be used as abstract base classes, at least one method needs to be pure virtual – but the classes don’t have virtual methods! So we make the destructor pure virtual instead.
It makes the class abstract. The existance of at least a pure virtual method is sufficient for a class to be abstract.
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