careercup-C和C++ 13.6
13.6 基类的析构函数为何要声明为virtual?
解答:
用对象指针来调用一个函数,有以下两种情况:
- 如果是虚函数,会调用派生类中的版本。
- 如果是非虚函数,会调用指针所指类型的实现版本。
析构函数也会遵循以上两种情况,因为析构函数也是函数嘛,不要把它看得太特殊。 当对象出了作用域或是我们删除对象指针,析构函数就会被调用。
当派生类对象出了作用域,派生类的析构函数会先调用,然后再调用它父类的析构函数, 这样能保证分配给对象的内存得到正确释放。
但是,如果我们删除一个指向派生类对象的基类指针,而基类析构函数又是非虚的话, 那么就会先调用基类的析构函数(上面第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的更多相关文章
- [CareerCup] 17.13 BiNode 双向节点
17.13 Consider a simple node-like data structure called BiNode, which has pointers to two other node ...
- [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 ...
- [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行,最 ...
- [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 ...
- [CareerCup] 13.3 Virtual Functions 虚函数
13.3 How do virtual functions work in C++? 这道题问我们虚函数在C++中的工作原理.虚函数的工作机制主要依赖于虚表格vtable,即Virtual Table ...
- [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. 这道题问 ...
- [CareerCup] 13.5 Volatile Keyword 关键字volatile
13.5 What is the significance of the keyword "volatile" in C 这道题考察我们对于关键字volatile的理解,顾名思义, ...
- [CareerCup] 13.6 Virtual Destructor 虚析构函数
13.6 Why does a destructor in base class need to be declared virtual? 这道题问我们为啥基类中的析构函数要定义为虚函数.首先来看下面 ...
- [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 ...
- [CareerCup] 13.8 Smart Pointer 智能指针
13.8 Write a smart pointer class. A smart pointer is a data type, usually implemented with templates ...
随机推荐
- OS.ENVIRON()详解
OS.ENVIRON()详解
- SharePoint 2010 出错! HTTP Error 503. The service is unavailable
转:http://544729.blog.51cto.com/534729/464087 昨天,公司的sharepoint 2010 无法打开,提示HTTP Error 503. The servic ...
- Myeclipse *.link用法
引用路径 path=D:\\ProgramData\\MyEclipse\\adt
- 【JMeter】JMeter使用plugins插件进行服务器性能监控
性能测试时,我们的关注点有两部分 1 服务本身:并发 响应时间 QPS 2 服务器的资源使用情况:cpu memory I/O disk等 JMeter的plugins插件可以实现对"二&q ...
- 【JMeter】JMeter完成一个java请求的压测
先定义一下我说的remoteService:即远程调用服务,没有http的url.不对外提供或者对外提供有限的服务.具体视各公司的代码架构所定,比如有些公司为web工程,scf服务,db.scf即为服 ...
- HUST 1017 Exact cover dance links
学习:请看 www.cnblogs.com/jh818012/p/3252154.html 模板题,上代码 #include<cstdio> #include<cstring> ...
- HDU 5637 Transform 搜索
题意:bc round 74 div1 1002 中文题 分析(官方题解):注意到答案实际上只和s⊕t有关, bfs预处理下从0到xx的最短步数, 然后查询O(1)回答即可. #include < ...
- Python 连接mysql
下面我们使用MySQLdb 实现连接mysql 数据库并进行操作. #!/usr/bin/env python # -*-coding:UTF-8-*- import MySQLdb def conn ...
- error C2065:未声明的标识符错误
原文地址:http://blog.sina.com.cn/s/blog_8216ada701017evx.html 在VS2010下进行VC++调试时,出现这样一种错误:error C2065:未声明 ...
- [LeetCode]切割字符串,使各个子串都是回文
题目:Given a string s, partition s such that every substring of the partition is a palindrome. Return ...