13.6 基类的析构函数为何要声明为virtual?

解答:

用对象指针来调用一个函数,有以下两种情况:

  1. 如果是虚函数,会调用派生类中的版本。
  2. 如果是非虚函数,会调用指针所指类型的实现版本。

析构函数也会遵循以上两种情况,因为析构函数也是函数嘛,不要把它看得太特殊。 当对象出了作用域或是我们删除对象指针,析构函数就会被调用。

当派生类对象出了作用域,派生类的析构函数会先调用,然后再调用它父类的析构函数, 这样能保证分配给对象的内存得到正确释放。

但是,如果我们删除一个指向派生类对象的基类指针,而基类析构函数又是非虚的话, 那么就会先调用基类的析构函数(上面第2种情况),派生类的析构函数得不到调用。

例如:

class Foo
{
public:
void f();
}; class Bar: public Foo
{
public:
void f();
} Foo *p=new Bar();
p->f();

调用p->f()最后将会调用Foo::f(),这是因为p是指向Foo的指针,而f()不是虚函数。

为确保p->f()会调用继承关系最末端的子类的f()实现,我们需要将f()声明为虚函数。

现在,回到前面的析构函数。析构函数用于释放内存和资源。Foo的析构函数若不是虚拟的,那么,即使p实际上是Bar类型的,还是会调用Foo的析构函数。

这就是为何要将析构函数声明为虚拟的原因——确保正确调用继承关系最末端的子类的析构函数

例如:

class Base{
public:
Base() { cout<<"Base Constructor"<<endl; }
~Base() { cout<<"Base Destructor"<<endl; }
};
class Derived: public Base{
public:
Derived() { cout<<"Derived Constructor"<<endl; }
~Derived() { cout<<"Derived Destructor"<<endl; }
};
int main(){
Base *p = new Derived();
delete p;
return ;
}

输出为:

Base Constructor
Derived Constructor
Base Destructor

上面结果表明,虽然基类指向的是派生类,但是调用析构函数释放p时,仍然只调用了基类的析构函数。

如果我们把基类的析构函数声明为虚析构函数,这会使得所有派生类的析构函数也为虚。 从而使析构函数得到正确调用。

将基类的析构函数声明为虚的之后,得到的输出是:

Base Constructor
Derived Constructor
Derived Destructor
Base Destructor

因此,如果我们可能会删除一个指向派生类的基类指针时,应该把析构函数声明为虚函数。 事实上,《Effective C++》中的观点是,只要一个类有可能会被其它类所继承, 就应该声明虚析构函数。

careercup-C和C++ 13.6的更多相关文章

  1. [CareerCup] 17.13 BiNode 双向节点

    17.13 Consider a simple node-like data structure called BiNode, which has pointers to two other node ...

  2. [CareerCup] 18.13 Largest Rectangle of Letters

    18.13 Given a list of millions of words, design an algorithm to create the largest possible rectangl ...

  3. [CareerCup] 13.1 Print Last K Lines 打印最后K行

    13.1 Write a method to print the last K lines of an input file using C++. 这道题让我们用C++来打印一个输入文本的最后K行,最 ...

  4. [CareerCup] 13.2 Compare Hash Table and STL Map 比较哈希表和Map

    13.2 Compare and contrast a hash table and an STL map. How is a hash table implemented? If the numbe ...

  5. [CareerCup] 13.3 Virtual Functions 虚函数

    13.3 How do virtual functions work in C++? 这道题问我们虚函数在C++中的工作原理.虚函数的工作机制主要依赖于虚表格vtable,即Virtual Table ...

  6. [CareerCup] 13.4 Depp Copy and Shallow Copy 深拷贝和浅拷贝

    13.4 What is the difference between deep copy and shallow copy? Explain how you would use each. 这道题问 ...

  7. [CareerCup] 13.5 Volatile Keyword 关键字volatile

    13.5 What is the significance of the keyword "volatile" in C 这道题考察我们对于关键字volatile的理解,顾名思义, ...

  8. [CareerCup] 13.6 Virtual Destructor 虚析构函数

    13.6 Why does a destructor in base class need to be declared virtual? 这道题问我们为啥基类中的析构函数要定义为虚函数.首先来看下面 ...

  9. [CareerCup] 13.7 Node Pointer 节点指针

    13.7 Write a method that takes a pointer to a Node structure as a parameter and returns a complete c ...

  10. [CareerCup] 13.8 Smart Pointer 智能指针

    13.8 Write a smart pointer class. A smart pointer is a data type, usually implemented with templates ...

随机推荐

  1. FJOI2007轮状病毒

    不会推公式…… 不会基尔霍夫矩阵…… 不会matrix—tree定理…… 膜拜vfleaking大神…… 题解:http://z55250825.blog.163.com/blog/static/15 ...

  2. I.MX6 gpio-keys driver hacking

    /**************************************************************************** * I.MX6 gpio-keys driv ...

  3. Java [leetcode 12] Integer to Roman

    题目描述: Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range fr ...

  4. (Android Studio)添加文本框

    此文大部分摘自http://hukai.me/android-training-course-in-chinese/basics/firstapp/building-ui.html android : ...

  5. Proguard使用教程

    一.概念 ProGuard是一款免费的Java类文件压缩器.优化器和混淆器.它能发现并删除无用类.字段(field).方法和属性值(attribute).它也能优化字节码并删除无用的指令.最后,它使用 ...

  6. JSON 格式的转换: 数组、字符串、List集合、DataTable,实体对象

    JSON验证工具:http://jsonlint.com/JSON简明教程:http://www.w3school.com.cn/json/Newtonsoft.Json类库下载:http://jso ...

  7. iOS程序性能优化

    iOS程序性能优化 一.初级 使用ARC进行内存管理 在iOS5发布的ARC,它解决了最常见的内存泄露问题.但是值得注意的是,ARC并不能避免所有的内存泄露.使用ARC之后,工程中可能还会有内存泄露, ...

  8. CentOS上安装MyCat-MySQL

    1.安装JDK,要求JDK7以上. 2.下载MyCat,地址. 3.解压Mycat-server-1.6-RELEASE-20161028204710-linux.tar.gz,到usr/local/ ...

  9. Mac java环境配置

    进入命令行 cd ~ touch .bash_profile vi .bash_profile 输入内容jdk变量配置内容: export JAVA_HOME=/Library/Java/JavaVi ...

  10. Java 8 开发顶级技巧

    本文由码农网 – 小峰原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! 我使用Java 8编码已经有些年头,既用于新的应用程序,也用来迁移现有的应用,感觉是时候写一些我发现的非常有用的 ...