base class의 소멸자를 virtual 로 선언하지 않았을 때 문제점

class TimeKeeper {
public:
    TimeKeeper() {}
    ~TimeKeeper() {} // 비가상 소멸자
};

class AtomicClock: public TimeKeeper {
public:
    AtomicClock() {}
    ~AtomicClock() { std::cout << "AtomicClock destroyed\\n"; }
};

TimeKeeper* getTimeKeeper() {
    return new AtomicClock(); // 실제로는 AtomicClock 객체 생성
}

TimeKeeper* tk = getTimeKeeper(); // TimeKeeper 포인터로 AtomicClock 객체를 받음
delete tk; // TimeKeeper의 소멸자만 호출, AtomicClock의 소멸자는 호출되지 않음!

해결 방법


가상 소멸자가 필요 없는 경우

class Point { // 2D 좌표를 나타냄
public:
    Point(int xCoord, int yCoord);
    ~Point();
private:
    int x, y;
};