如果子类构造函数没有显式指明基类部分(基类子对象)的初始化方式,那么编译器将会自动调用基类的无参构造函数来初始化基类子对象。
如果希望以有参的方式来初始化基类部分,那么必须使用初始化列表来显式指明
子对象构造顺序
#include <iostream>
using namespace std;
class Member{
private:
int m_m;
public:
Member(){
cout << "Member()" << endl;
}
Member(int m) {
cout << "Member(int)" << endl;
m_m = m;
}
};
class Base {
private:
int m_i;
public:
Base(){
cout << "Base()" << endl;
}
Base(int i){
cout << "Base(int)" << endl;
m_i = i;
}
};
class Derived:public Base{
private:
int m_d;
Member m_me;
public:
Derived(){
cout << "Derived()" << endl;//不指定作用域 默认调用无惨构造函数
}
Derived(int d):Base(d), m_me(d){ //指定作用域 就调用有参构造函
cout << "Derived(int)" << endl;
m_d = d;
}
};
int main (void) {
Derived d1;
Derived d2(100);
return 0;
}
子类的析构函数,无论自己定义的,还是编译器缺省提供,都会自动调用基类的析构函数,完成基类子对象的销毁
子类对象销毁过程
#include <iostream>
using namespace std;
class Member{
private:
int m_m;
public:
Member(){
cout << "Member()" << endl;
}
Member(int m) {
cout << "Member(int)" << endl;
m_m = m;
}
~Member(){
cout << "~Member()" << endl;
}
};
class Base {
private:
int m_i;
public:
Base(){
cout << "Base()" << endl;
}
Base(int i){
cout << "Base(int)" << endl;
m_i = i;
}
~Base(){
cout << "~Base()" << endl;
}
};
class Derived:public Base{
private:
int m_d;
Member m_me;
public:
Derived(){
cout << "Derived()" << endl;//不指定作用域 默认调用无惨构造函数
}
Derived(int d):Base(d), m_me(d){ //指定作用域 就调用有参构造函
cout << "Derived(int)" << endl;
m_d = d;
}
~Derived(){
cout << "~Derived()" << endl;
}
};
int main (void) {
Derived d1;
return 0;
}
//输出结果:
myubuntu@ubuntu:~/lv19/cplusplus/dy03$ ./a.out
Base()
Member()
Derived()
~Derived()
~Member()
~Base()