-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirtual-destructors.cpp
38 lines (30 loc) · 977 Bytes
/
virtual-destructors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// https://www.youtube.com/watch?v=jELbKhGkEi0&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=68
// lesson: if a class has a possibility of being subclassed, always declare the destructor as virtual
#include <iostream>
class Base
{
public:
Base() { std::cout << "Base Constructor" << std::endl; }
virtual ~Base() { std::cout << "Base Destructor" << std::endl; } // important line
};
class Derived : public Base
{
public:
Derived() { std::cout << "Derived Constructor" << std::endl; }
~Derived() { std::cout << "Derived Destructor" << std::endl; }
};
int main()
{
Base *base = new Base();
delete base;
// everything works as expected
std::cout << std::endl;
Derived *derived = new Derived();
delete derived;
// everything works as expected
std::cout << std::endl;
Base *poly = new Derived();
delete poly;
// if the base destructor is not marked as virtual
// then the derived destructor will not be called
}