Can a destructor be pure virtual in C++?
Yes, it is possible to have pure virtual destructor. Pure virtual destructor are legal in standard C++ and one of the most important thing is that if class contains pure virtual destructor it is must to provide a function body for the pure virtual destructor. This seems strange that how a virtual function is pure if it requires a function body? But destructors are always called in the reverse order of the class derivation. That means derived class destructor will be invoked first & then base class destructor will be called. If definition for the pure virtual destructor is not provided then what function body will be called during object destruction? Therefore compiler & linker enforce existence of function body for pure virtual destructor.
Consider following program:
The linker will produce following error in the above program.
test.cpp:(.text$_ZN7DerivedD1Ev[__ZN7DerivedD1Ev]+0x4c): undefined reference to `Base::~Base()'
Now if the definition for the pure virtual destructor is provided then the program compiles & runs fine.
~Derived() is executed Pure virtual destructor is called
It is important to note that class becomes abstract class when it contains pure virtual destructor. For example try to compile the below program.
The above program fails in compilation & shows following error messages.
[Error] cannot declare variable ‘p’ to be of abstract type ‘Test’
[Note] because the following virtual functions are pure within ‘Test’:
[Note] virtual Test::~Test()
[Error] cannot allocate an object of abstract type ‘Test’
[Note] since type ‘Test’ has pure virtual functions
This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Virtual Destructor
- Pure Virtual Functions and Abstract Classes in C++
- Calling virtual methods in constructor/destructor in C++
- Pure Functions
- Private Destructor
- Order of Constructor/ Destructor Call in C++
- Is it possible to call constructor and destructor explicitly?
- What happens when a virtual function is called inside a non-virtual function in C++
- __attribute__((constructor)) and __attribute__((destructor)) syntaxes in C
- Virtual Function in C++
- Virtual destruction using shared_ptr in C++
- Advanced C++ | Virtual Constructor
- Virtual base class in C++
- C++ | Virtual Functions | Question 1
- C++ | Virtual Functions | Question 2