copy constructor

复制代码
#include<iostream>
using namespace std;
class A
{
public:
     A(){ cout <<"1";}
     A(const A &obj){ cout <<"2";}
};

class B: virtual A
{
public:
    B(){cout <<"3";}
    B(const B & obj){cout<<"4";}
};

class C: virtual A
{
public:
   C(){cout<<"5";}
   C(const C & obj){cout <<"6";}
};

class D:B,C
{
public:
    D(){cout<<"7";}
    D(const D & obj){cout <<"8";}
};

int main()
{
   D d1;
   D d(d1);
}
复制代码

Output will be 13571358 as 1357 (for D d1) and as 1358 (for D d(d1))......reason is that ......during inheritance we need to explicitly call copy constructor of base class otherwise only default constructor of base class is called. One more thing, as we are using virtual before base class, there will be only one copy of base class in multiple inheritance. And without virtual output will be......13157....&...13158 as (1315713158) respectively for each derived class object.

 

ref http://quiz.geeksforgeeks.org/c-plus-plus/inheritance/    question 14

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值