C++学习笔记——多继承机制下构造函数的调用顺序(2)

       如果派生类有一个虚基类作为祖先类,那么在派生类构造函数的初始化列表中需要对虚基类构造函数的调用,如果未列出则表明用的是虚基类的无参数构造函数。
       不管初始化列表中次序如何,对虚基类构造函数的调用总是先于先于普通基类的构造函数。
       虚基类的唯一副本只被初始化一次。
举个例子:
基类:
class Base1
{
public:
	Base1() { cout << "Constructing Base1" << endl; }
};
class Base2
class Base2
{
public:
	Base2() { cout << "Constructing Base2" << endl; }
};
派生类:
class Derived1 :public Base2, virtual public Base1
{
public:
	Derived1() { cout << "Constructing Derived1 " << endl; }
};
class Derived2 :public Base2, virtual public Base1
{
public:
	Derived2() { cout << "Constructing Derived2" << endl; }
};
class Derived3 :public Derived1, virtual public Derived2
{
public:
	Derived3() { cout << "Constructing Derived3" << endl; }
};
主函数:
int main()
{
	Derived3 obj;
	return 0;
}
代码分析:
       1、关系图:

关系图

       2、思路整理

       根据前文,程序初始化时,先执行虚基类,Derived2 => Derived1 => Derived3;
              Derived2中,先执行虚基类,Base1 => Base2 => Derived2;
              Derived1中,先执行虚基类,Base1 => Base2 => Derived1;
              最后执行Derived3,结束。
       这样对吗?不对。因为Base1作为虚基类被初始化了两次!!!

运行结果:
Constructing Base1
Constructing Base2
Constructing Derived2
Constructing Base2
Constructing Derived1
Constructing Derived3
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值