#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base()
{
cout << "~Base()" << "\n";
}
};
class Derived : public Base
{
private:
int *m_array;
public:
Derived(int length)
{
m_array = new int[length];
}
virtual ~Derived() override // 부모 클래스 소멸자에 virtual을 적어줘야 override 가능
{
cout << "~Derived" << "\n";
delete[] m_array;
}
};
int main()
{
// Derived derived(5); // 상속 순서에 따라 자식클래스-부모클래스 순으로 소멸자가 호출된다. 생성자 호출 순서와 반대.
Derived *derived = new Derived(5);
Base *base = derived;
delete base; // 자식 클래스는 여러개가 있기 때문에 지우려면 base를 지우는게 편하다. 하지만 derived에 있는 메모리가 누수가 된다.
// 때문에 Base 소멸자에 virtual을 해주면 자식 클래스의 소멸자를 호출하고 부모 클래스의 소멸자를 호출하게 된다.
return 0;
}