【发布时间】:2011-02-05 05:35:23
【问题描述】:
这个问题听起来可能太傻了,但是,我在其他任何地方都找不到具体的答案。
对后期绑定的工作原理和继承中使用的虚拟关键字知之甚少。
如在代码示例中,在继承的情况下,当使用指向在堆上创建的派生类对象的基类指针和删除运算符来释放内存时,将调用派生类和基类的析构函数仅当基析构函数声明为虚函数时才按顺序排列。
现在我的问题是:
1) 当base的析构函数不是virtual时,为什么只有在使用“delete”操作符的情况下才会出现不调用派生dtor的问题,为什么不是下面给出的情况:
derived drvd;
base *bPtr;
bPtr = &drvd; //DTOR called in proper order when goes out of scope.
2) When "delete" operator is used, who is reponsible to call the destructor of the class? The operator delete will have an implementation to call the DTOR ? or complier writes some extra stuff ? If the operator has the implementation then how does it looks like , [I need sample code how this would have been implemented].
3) If virtual keyword is used in this example, how does operator delete now know which DTOR to call?
Fundamentaly i want to know who calls the dtor of the class when delete is used.
<h1> Sample Code </h1>
class base
{
public:
base(){
cout<<"Base CTOR called"<<endl;
}
virtual ~base(){
cout<<"Base DTOR called"<<endl;
}
};
class derived:public base
{
public:
derived(){
cout<<"Derived CTOR called"<<endl;
}
~derived(){
cout<<"Derived DTOR called"<<endl;
}
};
I'm not sure if this is a duplicate, I couldn't find in search.
int main()
{
base *bPtr = new derived();
delete bPtr;// only when you explicitly try to delete an object
return 0;
}
【问题讨论】:
-
小点,但你的问题说多重继承。这不是多重继承的例子,它只是普通的旧继承。
标签: c++ inheritance