Learn c++ virtual destructor in 15 minutes, maybe in 8 minutes, even in 2 minutes if you can, as it has one key point only.
You have learned the virtual method from previous tutorial: polymorphism virtual method (day-13).
The destructor have to be virtual sometimes.
class class_a { public: virtual ~class_a() // virtual destructor. { } };
Let us see the polymorphism program with no-virtual destructor.
// An issue c++ program.
#include <iostream> class base_class { public: base_class() // constructor { std::cout << "Create base object" << std::endl; } ~base_class() // destructor: no virtual { std::cout << "Remove base object" << std::endl; } }; class derived_class: public base_class { public: derived_class() { std::cout << "Create derived object" << std::endl; } ~derived_class() { std::cout << "Remove derived object" << std::endl; } }; int main() { base_class * ptr = new derived_class{}; delete ptr; }
Compile and run the code:
>>> g++ hello.cpp -std=c++23 -o hello >>> ./hello Create base object Create derived object Remove base object
You see,
base object is created once, and removed once.
derived object is created once, but never removed !
To solve the above issue, the virtual destructor is the solution.
Add virtual specifier to the destructor of the base class.
virtual ~base_class() // virtual destructor { // other code ... }
You have learned from the previous tutorial the virtual method for the polymorpihsm,
virtual method makes that method polymorphism.
The destructor
must be made polymorphism too, by using virtual destructor.
According to cppreference:
quote:
Note | |
---|---|
Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual: class Base { public: virtual ~Base() {} }; class Derived : public Base {}; Base* b = new Derived; delete b; // safe |
Written on Nov 05, 2024
c++ std::exception:
std::cout.write(err.data(), err.size());
std::cout << std::endl;
caught:
=================================== # The c++ programming language. # # # # Join c++ Discord: yZcauUAUyC # # Deck # ===================================