Home >Backend Development >C++ >Should Abstract Base Classes Have Pure Virtual Destructors?
Pure Virtual Destructors in C : A Cautionary Tale
The usage of pure virtual destructors in C can raise concerns, particularly in the context of abstract base classes. Let's delve into a scenario and its potential consequences.
Question:
Is it acceptable to define an abstract base class with a pure virtual destructor, as seen in the following example?
class A { public: virtual ~A() = 0; };
Answer:
No. Defining an abstract base class with a pure virtual destructor alone is insufficient. It potentially leads to undefined behavior.
When an object is deleted or destroyed, the destructors of its base classes are called in reverse order of their declaration. If an abstract base class has a pure virtual destructor without an implementation, the compiler will not generate code for it.
This absence of an implementation means that when a derived class is deleted, the pure virtual destructor of the abstract base class will be called, invoking undefined behavior. In some cases, this may result in a crash.
Solution:
To resolve this issue, it is essential to implement the pure virtual destructor in the abstract base class. The following definition should suffice:
class A { public: virtual ~A() = 0; }; inline A::~A() { }
This implementation provides a default implementation that does nothing. By defining this inline destructor with no implementation, we ensure that the pure virtual destructor is implemented without affecting the functionality of derived classes.
It is worth noting that if you derive any classes from A and attempt to delete or destroy them, A's destructor will eventually be called. Hence, it is crucial to implement the pure virtual destructor to avoid undefined behavior and potential crashes.
The above is the detailed content of Should Abstract Base Classes Have Pure Virtual Destructors?. For more information, please follow other related articles on the PHP Chinese website!