Home > Backend Development > C++ > Why Must Pure Virtual Destructors in C Be Defined, Not Just Declared?

Why Must Pure Virtual Destructors in C Be Defined, Not Just Declared?

Linda Hamilton
Release: 2024-12-15 20:16:16
Original
292 people have browsed it

Why Must Pure Virtual Destructors in C   Be Defined, Not Just Declared?

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;
};
Copy after login

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() { }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template