Home > Backend Development > C++ > Should Pure Virtual Destructors in C Be Defined?

Should Pure Virtual Destructors in C Be Defined?

Linda Hamilton
Release: 2024-12-16 17:46:10
Original
195 people have browsed it

Should Pure Virtual Destructors in C   Be Defined?

Defining Pure Virtual Destructors in C : Unveiling the Pitfalls

The concept of pure virtual destructors in C raises important questions regarding the correct implementation for abstract base classes. Consider the following code snippet:

class A {
public:
    virtual ~A() = 0;
};
Copy after login

The question arises as to whether this approach is appropriate for defining an abstract base class. While it compiles successfully in MSVC, concerns exist that it may result in runtime crashes.

Unveiling the Problem

The issue stems from the lack of implementation for the pure virtual destructor. When derived classes are created from A, their destructors will eventually invoke A's destructor. However, since A's destructor is pure, the call will result in undefined behavior.

Resolving the Pitfall

To avoid this runtime crash, it is essential to implement the destructor in the base class itself. A simple inline implementation, as shown below, will suffice:

class A {
public:
    virtual ~A() = 0;
};

inline A::~A() { }
Copy after login

This implementation ensures that when any derived class is deleted or destroyed, A's destructor will be called and the program will behave as expected.

The above is the detailed content of Should Pure Virtual Destructors in C Be Defined?. 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