Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of pure virtual destructor? [duplicate]

Tags:

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?)

like image 598
iammilind Avatar asked Jul 28 '11 09:07

iammilind


People also ask

What is the purpose of virtual destructor?

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.

What is the purpose of virtual destructor Mcq?

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.

What is the use of virtual destructor in C++?

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.

Does a pure virtual class need a virtual destructor?

Pure virtual destructors in C++ To work correctly, classes with virtual methods must also have virtual destructors.


2 Answers

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.

like image 82
Konrad Rudolph Avatar answered Sep 27 '22 20:09

Konrad Rudolph


It makes the class abstract. The existance of at least a pure virtual method is sufficient for a class to be abstract.

like image 35
Luchian Grigore Avatar answered Sep 27 '22 19:09

Luchian Grigore