Virtual Destructor (C++)

Categories:

Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior.

Non-virtual Destructor

Code

 1#include <iostream>
 2
 3using namespace std;
 4
 5struct A {
 6    A() { cout << __PRETTY_FUNCTION__ << endl; }
 7    ~A() { cout << __PRETTY_FUNCTION__ << endl; }
 8};
 9
10struct B : public A {
11    B() { cout << __PRETTY_FUNCTION__ << endl; }
12    ~B() { cout << __PRETTY_FUNCTION__ << endl; }
13};
14
15int main() {
16    A *a = new B();
17
18    delete a;
19
20    return 0;
21}

Result

A::A()
B::B()
A::~A()

Virtual Destructor

Code

 1#include <iostream>
 2
 3using namespace std;
 4
 5struct A {
 6    A() { cout << __PRETTY_FUNCTION__ << endl; }
 7    virtual ~A() { cout << __PRETTY_FUNCTION__ << endl; }
 8};
 9
10struct B : public A {
11    B() { cout << __PRETTY_FUNCTION__ << endl; }
12    virtual ~B() { cout << __PRETTY_FUNCTION__ << endl; }
13};
14
15int main() {
16    A *a = new B();
17
18    delete a;
19
20    return 0;
21}

Result

A::A()
B::B()
virtual B::~B()
virtual A::~A()

See Also