Question about pure virtual destructor
Asked Answered
C

4

7

If we define a abstract class which has a pure virtual destructor, why do we have to give a definition of a destructor in the abstract class?

Calvinna answered 16/6, 2009 at 2:27 Comment(1)
Duplicate https://mcmap.net/q/129970/-pure-virtual-destructor-in-cStethoscope
S
15

The destructor for the base class must be called when the object is destroyed, so it needs a definition.

Seethe answered 16/6, 2009 at 2:31 Comment(0)
M
9

As pointed out by Jesse, inherited destructors always get called (they are called for you by the compiler with no way to override this behavior), so it stands to reason that a virtual destructor must have an implementation. So if a pure virtual destructor must have an implementation, what is the difference between a pure virtual destructor and a regular virtual destructor? If your abstract class has only the virtual destructor declared and no other pure virtual methods, making the destructor pure will prevent somebody from being able to instantiate the abstract class.

Maharani answered 16/6, 2009 at 2:47 Comment(0)
O
9

Because the standard says so:

12.4.7 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.

The reason for this is that it is called explicitly when an object of a derived class is destroyed.

See also the answers to my previous question: Under what circumstances is it advantageous to give an implementation of a pure virtual function?

Ophicleide answered 16/6, 2009 at 8:28 Comment(1)
It is not correct to say that it is called "explicitly". It was helpful that you referenced the standard, but you should edit your answer so that it is more formally correct. "explicitly" is the opposite of how destructors are normally called.Starspangled
C
3

Only a virtual dtor can be declared as pure. But then, since you add a declaration, you must implement the body of the dtor. As already mentioned, the destructors call their parent dtor, all up to the chain of inheritance.

Croton answered 16/6, 2009 at 3:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.