Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a pure virtual destructor needs an implementation

I know the cases where pure virtual destructors are needed. I also know that If we don't provide an implementation for them it will give me a linker error. What I don't understand is why this should be the case in a code fragment as shown below:

int main()
{
    Base * p = new Derived;
}

Here there is no delete, so no call to destructor and so no need for its implementation(assuming it is supposed to behave like other normal functions which are declared but not defined, linker complains only when we call them)...or am I missing something?

I need to understand why this should be a special case?

Edit: based on comments from BoBTFish

Here are my Base and Derived classes

class Base
{
public:
    Base(){}
    virtual ~Base() = 0;
};

class Derived : public Base
{
};
like image 312
Arun Avatar asked Jan 14 '14 09:01

Arun


People also ask

Why would we want to should we use a pure virtual destructor?

When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance.

What is the basic purpose of virtual destructor why and when we have to implement it write briefly?

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.

Why do we need deconstructor?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

What happens if virtual Desctructor is not used in C++?

Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior.


1 Answers

C++11 standard:

12.4 Destructors

Paragraph 9:

A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined. If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.
like image 114
Spook Avatar answered Sep 18 '22 12:09

Spook