C++ | Inheritance | Question 12

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
class Base
{
protected:
    int a;
public:
    Base() {a = 0;}
};
  
class Derived1:  public Base
{
public:
    int c;
};
  
  
class Derived2:  public Base
{
public:
    int c;
};
  
class DerivedDerived: public Derived1, public Derived2
{
public:
    void show()  {   cout << a;  }
};
  
int main(void)
{
    DerivedDerived d;
    d.show();
    return 0;
}

chevron_right


(A) Compiler Error in Line “cout << a;"
(B) 0
(C) Compiler Error in Line “class DerivedDerived: public Derived1, public Derived2”


Answer: (A)

Explanation: This is a typical example of diamond problem of multiple inheritance. Here the base class member ‘a’ is inherited through both Derived1 and Derived2. So there are two copies of ‘a’ in DerivedDerived which makes the statement “cout << a;" ambiguous.

The solution in C++ is to use virtual base classes. For example, the following program works fine and prints

#include<iostream>
using namespace std;

class Base
{
protected:
int a;
public:
Base() {a = 0;}
};

class Derived1: virtual public Base
{
public:
int c;
};

class Derived2: virtual public Base
{
public:
int c;
};

class DerivedDerived: public Derived1, public Derived2
{
public:
void show() { cout << a; }
};

int main(void)
{
DerivedDerived d;
d.show();
return 0;
}


Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.