class Trans
{
public:
Trans();
virtual void logTrans() const
{
cout<<"parent class called"<<endl;
}
};
Trans::Trans()
{
logTrans();
}
class BuyTrans : public Trans
{
public:
virtual void logTrans() const
{
cout<<"child class called"<<endl;
}
};
int main()
{
Trans *p;
p = new BuyTrans;
p->logTrans();
return 0;
}
결과
parent class called
child class called
첫번째 parent class 생성자가 호출된 이유
new 할때 부모클래스 생성자에서 logTrans 를 호출을 하는데 virtual 로 되어 있어서 자식클래스에 있는 logTrans 를 호출할거 같지만 문제는 자식클래스는
아직 완료되지 않은 상태이다
그래서 부모 클래스의 logTrans 가 호출이 된다.
그래서 부모 클래스의 logTrans 가 호출이 된다.
그 다음 p->logTrans는 자식클래스의 생성자가 완료되고 나서 정상적으로
virtual 함수에 의해서 자식클래스의 logTrans 가 호출이 된다.
중요!! 생성자 때 오버라이드 된 함수를 호출시 자식클래스의 함수를 호출할 거라는 기대를 하지 말자 (소멸자도 동일)