Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ multiple inheritance function call ambiguity

I have a basic question related to multiple inheritance in C++. If I have a code as shown below:

struct base1 {    void start() { cout << "Inside base1"; } };  struct base2 {    void start() { cout << "Inside base2"; } };  struct derived : base1, base2 { };  int main() {   derived a;   a.start(); } 

which gives the following compilation error:

1>c:\mytest.cpp(41): error C2385: ambiguous access of 'start' 1>      could be the 'start' in base 'base1' 1>      or could be the 'start' in base 'base2' 

Is there no way to be able to call function start() from a specific base class using a derived class object?

I don't know the use-case right now but.. still!

like image 695
goldenmean Avatar asked Jul 27 '11 14:07

goldenmean


People also ask

Does multiple inheritance lead to ambiguity?

The ambiguity that arises when using multiple inheritance refers to a derived class having more than one parent class that defines property[s] and/or method[s] with the same name. For example, if 'C' inherits from both 'A' and 'B' and classes 'A' and 'B', both define a property named x and a function named getx().

How can we resolve ambiguity in multiple inheritance?

You can resolve ambiguity by qualifying a member with its class name using the scope resolution ( :: ) operator. The statement dptr->j = 10 is ambiguous because the name j appears both in B1 and B2 . The statement dobj.

Which type of inheritance leads to ambiguity problem?

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

What is ambiguity concept in multiple inheritance?

Ambiguity in inheritance can be defined as when one class is derived for two or more base classes then there are chances that the base classes have functions with the same name. So it will confuse derived class to choose from similar name functions.


1 Answers

a.base1::start();  a.base2::start(); 

or if you want to use one specifically

class derived:public base1,public base2 { public:     using base1::start; }; 
like image 93
dascandy Avatar answered Sep 30 '22 07:09

dascandy