Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Inheritance: same variable name

class A
{
   protected:
    string word;
};

class B
{
   protected:
    string word;
};

class Derived: public A, public B
{

};

How would the accessibility of the variable word be affected in Derived? How would I resolve it?

like image 685
Jack Smother Avatar asked Nov 04 '13 08:11

Jack Smother


People also ask

What is the common mistake in using multiple inheritance?

Multiple inheritance has been a controversial issue for many years, with opponents pointing to its increased complexity and ambiguity in situations such as the "diamond problem", where it may be ambiguous as to which parent class a particular feature is inherited from if more than one parent class implements said ...

Is it possible to use multilevel and multiple inheritances simultaneously?

Java supports only Single, Multilevel, and Hierarchical types of inheritance. Java does not support Multiple and Hybrid inheritance.

How multiple inheritance are represented?

Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B's constructor is called before A's constructor.

What shows multiple inheritance?

Multiple inheritance occurs when a class inherits from more than one base class. So the class can inherit features from multiple base classes using multiple inheritance. This is an important feature of object oriented programming languages such as C++.


2 Answers

It will be ambiguous, and you'll get a compilation error saying that.

You'll need to use the right scope to use it:

 class Derived: public A, public B
{
    Derived()
    {
        A::word = "A!";
        B::word = "B!!";
    }
};
like image 156
Yochai Timmer Avatar answered Sep 20 '22 12:09

Yochai Timmer


You can use the using keyword to tell the compiler which version to use:

class Derived : public A, public B
{
protected:
    using A::word;
};

This tells the compiler that the Derived class has a protected member word, which will be an alias to A::word. Then whenever you use the unqualified identifier word in the Derived class, it will mean A::word. If you want to use B::word you have to fully qualify the scope.

like image 31
Some programmer dude Avatar answered Sep 22 '22 12:09

Some programmer dude