Home > Backend Development > C++ > Should Abstract Base Classes in C Have Pure Virtual Destructors?

Should Abstract Base Classes in C Have Pure Virtual Destructors?

Linda Hamilton
Release: 2024-12-28 06:21:17
Original
807 people have browsed it

Should Abstract Base Classes in C   Have Pure Virtual Destructors?

Pure Virtual Destructors in C

In the world of object-oriented programming, abstract base classes often require pure virtual destructors. However, concerns arise when writing code like this:

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

This raises the question of whether it's acceptable for an abstract base class to have a purely virtual destructor. While Microsoft Visual C compiles it without issue, what happens at runtime?

The answer is: Undefined behavior. If an instance of a class derived from A is deleted or destroyed, A's destructor will be invoked. However, since it's purely virtual and lacks an implementation, this triggers undefined behavior. On certain platforms, this can result in the purecall handler being invoked, leading to a crash.

To avoid this, it's crucial to implement the destructor as well. A minimal implementation like this should suffice:

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

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

This way, when instances of derived classes are deleted, A's destructor won't cause undefined behavior.

The above is the detailed content of Should Abstract Base Classes in C Have Pure Virtual Destructors?. 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