Open In App

C++ | Inheritance | Question 13




#include<iostream>
using namespace std;
  
class Base1
{
public:
    char c;
};
  
class Base2
{
public:
    int c;
};
  
class Derived: public Base1, public Base2
{
public:
    void show()  { cout << c; }
};
  
int main(void)
{
    Derived d;
    d.show();
    return 0;
}

(A) Compiler Error in “cout << c;"
(B) Garbage Value
(C) Compiler Error in “class Derived: public Base1, public Base2”

Answer: (A)
Explanation: The variable ‘c’ is present in both super classes of Derived. So the access to ‘c’ is ambiguous. The ambiguity can be removed by using scope resolution operator.




#include<iostream>
using namespace std;
  
class Base1
{
public:
    char c;
};
  
class Base2
{
public:
    int c;
};
  
class Derived: public Base1, public Base2
{
public:
    void show()  { cout << Base2::c; }
};
  
int main(void)
{
    Derived d;
    d.show();
    return 0;
}

Quiz of this Question


Article Tags :