Skip to content
Related Articles

Related Articles

Improve Article

C++ | Inheritance | Question 14

  • Difficulty Level : Easy
  • Last Updated : 28 Jun, 2021

Consider the below C++ program.




#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);
}

Which of the below is not printed?

This question is contributed by Sudheendra Baliga
(A) 2
(B) 4
(C) 6
(D) All of the above


Answer: (D)

Explanation: 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.

Quiz of this Question

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :