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?
The destructor for the base class must be called when the object is destroyed, so it needs a definition.
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.
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?
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.
© 2022 - 2024 — McMap. All rights reserved.