LoginSignup
1
2

More than 5 years have passed since last update.

[C++] Why virtual destructors

Last updated at Posted at 2016-04-10

To explain the difference of virtual destructor and normal destructor, look at this two examples.

Normal Destructor

Code

class Enemy {
public:
    ~Enemy() { cout << "Enemy Destructor." << endl; }
};

class EnemyBoss : public Enemy {
public:
    ~EnemyBoss() { cout << "Enemy Boss Destructor." << endl; }
};

int main() {
    Enemy *e = new EnemyBoss();
    delete e; // Destroy the object
    return 0;
}

Output

Enemy Destructor.

Virtual destructor.

Code

class Enemy {
public:
    virtual ~Enemy() { cout << "Enemy Destructor." << endl; }
};

class EnemyBoss : public Enemy {
public:
    ~EnemyBoss() { cout << "Enemy Boss Destructor." << endl; }
};

int main() {
    Enemy *e = new EnemyBoss();
    delete e;
    return 0;
}

Output

Enemy Boss Destructor.
Enemy Destructor.

Conclusion

The virtual destructor is very useful when delete a instance of a derived class through the pointer of parent class.

When delete a instance of a derived class through the pointer of parent class, the virtual destructor will call the parent destructor, but the non-virtual destructor will not call the parent destructor. Therefore the second situation may potentially have the problem of memory leak.

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2