Create TOC

2000년 5월 15일

C++/Virtual Destructor

아래와 code를 보자.

class Sample {
public:
 Sample() { cout << "Sample" << endl; }
 ~Sample() { cout << "~Sample" << endl; }

};

class Derived : public Sample {
public:
 Derived() { cout << "Derived" << endl; }
 ~Derived() { cout << "~Derived" << endl; }
};


int main(int argc, char **argv)
{
 Sample *p = new Derived;

 delete p;
 return 0;
}

수행결과는 어떨까? 아마도

Sample
Derived
~Derived
~Sample

가 되어야 할 것처럼 보인다. 하지만 실제 수행해보면

Sample
Derived
~Sample

Derived의 destructor가 호출되지 않는 것을 볼 수 있다. 그 이유는 포인터 p는 Sample class 형 포인터 이기 때문에 Derived의 destructor을 알지 못한다. 따라서 위에 delete p 할 때 Sample의 destructor만을 호출하게 된다.

이 문제를 해결하기 위해서는 Simple class 에서 destructor 선언시 virtual 을 사용해야 한다.

virtual ~Sample() { cout << "~Sample" << endl; }