假设我有一个基类指针,基类具有虚函数。如果我使用基类指针指向派生类对象,那么编译器如何知道它是要调用的该虚函数的派生版本,因为在分配时派生类地址将被转换为基类类型,为什么不't 编译器会产生错误,因为两者的内存布局可能不同。
而且,如果我已声明基类析构函数为虚拟并删除具有派生类地址的基指针,那么编译器如何知道我实际上正在删除派生对象。
class a{
public:
virtual ~a(){}
virtual void f(){}
};
class b:public a
{
public:
~b(){}
void f(){ cout<<"hi";}
};
main()
{
a *aptr;
aptr=new b; //here aptr has the address of b;
delete aptr; //since pointer type is base class so how will compiler know that
//it has to call derived's destructor,also their names are different
//as one is a and another is b.
}