C++基类构造器的自动调用
虽然基类的构造器和解构器不会被派生类继承,但它们会被派生类的构造器和解构器自动调用,今天我们用代码实证一下。
验证代码
源代码,仔细看注释内容:
D:\YcjWork\CppTour>vim c2004.cpp
#include <iostream>
using namespace std;
/**
* 基类不同构造器的调用
*/
class Mother{
public:
Mother(){
cout << "Mother: no param" << endl;
}
Mother(int a){
cout << "Mother: int param" << endl;
}
~Mother(){
cout << "Deconstruction Mother" << "\n\n";
}
};
class Daughter: public Mother{
public:
Daughter(int a){ //派生类构造器调用基类的默认构造器Mother()
cout << "Daughter: int param" << "\n\n";
}
~Daughter(){
cout << "Deconstruction Daughter" << "\n";
}
};
class Son: public Mother{
public:
Son(int a): Mother(a){ //派生类构造器调用基类的指定构造器Mother(int a)
cout << "Son: int param" << "\n\n";
}
~Son(){
cout << "Deconstruction Son" << "\n";
}
};
int main(){
{
Daughter mary(5);
}
{
Son jack(6);
}
return 0;
}
编译运行
构造器的调用顺序:
先构造基类,再构造派生类
解构器的调用顺序:
先派生类解构,再基类解构
D:\YcjWork\CppTour>gpp c2004
D:\YcjWork\CppTour>g++ c2004.cpp -o c2004.exe
D:\YcjWork\CppTour>c2004
Mother: no param
Daughter: int param
Deconstruction Daughter
Deconstruction Mother
Mother: int param
Son: int param
Deconstruction Son
Deconstruction Mother
D:\YcjWork\CppTour>
运行截屏
(全文完)