Pure Virtual Destructors in C
In C , it's important to be mindful of the behavior of pure virtual destructors within abstract base classes. Although it may seem intuitive to declare a pure virtual destructor in a base class, as shown below:
class A { public: virtual ~A() = 0; };
this approach is incorrect and can lead to unexpected consequences.
Contrary to expectations, simply declaring a pure virtual destructor is not sufficient for an abstract base class. Implementing the destructor is also crucial. Here's how to properly implement a pure virtual destructor:
class A { public: virtual ~A() = 0; }; inline A::~A() { }
The empty inline destructor serves as a default implementation, ensuring that the destructor can be called without causing undefined behavior when destroying derived classes.
If you omit the definition of the destructor, any attempt to derive from class A and subsequently delete or destroy the derived object will invoke the purecall handler, potentially resulting in a program crash.
Therefore, when working with abstract base classes in C , remember to implement pure virtual destructors to prevent undefined behavior and ensure proper cleanup of resources.
The above is the detailed content of Why Must Pure Virtual Destructors in C Be Defined, Not Just Declared?. For more information, please follow other related articles on the PHP Chinese website!