vrb*_*lgi 4 c++ overriding object-lifetime virtual-destructor
让我声明:我对构造函数或析构函数中的虚函数调用有清楚的理解.
在下面的代码中,我试图避免虚拟析构函数仅用于实验目的.
现在我的问题是:
主要是对Destroy fun的调用调用正确的虚函数.我期待任何对Destroy Function的调用都应该调用正确的虚拟乐趣.
但是同样的Destroy函数放在Base析构函数调用的Base虚函数中.
这与静态绑定或编译器优化有关吗?
class Base
{
public:
Base()
{
}
void Destroy()
{
callVirtual();
}
virtual void callVirtual()
{
cout<<"In Base callVirtual "<<endl;
}
~ Base()
{
cout<<"In Base Destructor"<<endl;
Destroy();
}
};
Run Code Online (Sandbox Code Playgroud)
.
class Derived : public Base
{
public:
Derived()
{
}
void callVirtual()
{
cout"<<In Derived callVirtual"<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)
.
int main()
{
Base *pointer = new Derived();
pointer->Destroy(); // Calls the right callVirtual
return 0;
}
Run Code Online (Sandbox Code Playgroud)