기본 클래스에 대한 포인터를 사용하여 파생 클래스 개체를 삭제하려면 기본 클래스를 가상 소멸자로 정의해야 합니다.
예시 코드
#include<iostream>
using namespace std;
class b {
public:
b() {
cout<<"Constructing base \n";
}
virtual ~b() {
cout<<"Destructing base \n";
}
};
class d: public b {
public:
d() {
cout<<"Constructing derived \n";
}
~d() {
cout<<"Destructing derived \n";
}
};
int main(void) {
d *derived = new d();
b *bptr = derived;
delete bptr;
return 0;
} 출력
Constructing base Constructing derived Destructing derived Destructing base