가상 메커니즘은 파생 클래스 개체에 대한 기본 클래스 포인터가 있는 경우에만 작동합니다.
C++에서 생성자는 가상일 수 없습니다. 클래스의 생성자가 실행될 때 메모리에 가상 테이블이 없다는 것은 아직 가상 포인터가 정의되지 않았음을 의미하기 때문입니다. 따라서 생성자는 항상 가상이 아니어야 합니다.
하지만 가상 소멸자는 가능합니다.
예시 코드
#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