《Cracking the Coding Interview》——第13章:C和C++——题目6

2014-04-25 20:07

题目:为什么基类的析构函数必须声明为虚函数?

解法:不是必须,而是应该,这是种规范。对于基类中执行的一些动态资源分配,如果基类的析构函数不是虚函数,那么 派生类的析构函数在自动调用的时候,不会调用基类的析构函数,这样就会造成资源未释放引起的内存泄漏。

代码:

 // 13.6 If a class is defined as base class, why must its destructor be declared "virtual"?
// Answer:
// If the destructor of base class is declared "virtual", it will be called when a derived class object is being destroyed.
// Otherwise it wouldn't. As base class may already have some allocated data or other resources, the destructor of basic class must be called to clear them up.
// Missing the base class destructor will leave out those data allocated for base class, causing memory leakage.
// Even though there're no dynamically allocated data, the base class should be declared "virtual", as a good practice of coding.
class A {
public:
virtual ~A() {};
}; class B: public A {
public:
~B() {};
}; int main()
{
A *ptr = new B();
delete ptr;
// Here ~B() will be called first, ~A() to follow.
return ;
}
上一篇:二刷Cracking the Coding Interview(CC150第五版)


下一篇:em