默认构造
初始化构造 (有参数)
拷贝构造
移动构造(std::move 和 右值引用)
委托构造?
转换构造?
#include <iostream>
using namespace std;
class base
{
public:
base() { cout << "base constructor" << endl; }
~base() { cout << "base destructor" << endl; }
};
class derived : public base
{
public:
derived() { cout << "dervied constructor" << endl; }
~derived() { cout << "dervied destructor" << endl; }
};
int main()
{
base *pBase = new derived;
cout << "----" << endl;
delete pBase;
return 0;
}
/*
base constructor
dervied constructor
----
base destructor
*/
为什么析构函数有时要写为虚函数
如果基类的析构函数不是虚的,当通过基类指针删除指向派生类对象的对象时,只会调用基类的析构函数,而不会调用派生类的析构函数。这可能导致派生类的资源未被正确释放,造成内存泄漏。
<aside> <img src="/icons/light-bulb_gray.svg" alt="/icons/light-bulb_gray.svg" width="40px" /> 什么时候需要把析构函数写为虚函数
通常,如果一个类可能被继承,且在其派生类中有可能使用 delete 运算符来删除通过基类指针指向的对象,那么该基类的析构函数应该声明为虚析构函数。
</aside>
父类的成员变量不允许在初始化列表中初始化