How can I resolve a function call ambiguity when multiple base classes have a member function with the same name?
Asked Answered
C

3

47

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!

Castellated answered 27/7, 2011 at 14:10 Comment(4)
I shortened the snippet. No semantics were changed.Pendentive
Similar to #4832259Kinakinabalu
Rename the functions start1 and start2.Pyramidon
@JohnPaul not the same though; this one is about two base classes with an identical function, that one is about two base classes that have a function with the same name, but differing arguments.Aero
A
96
a.base1::start();

a.base2::start();

or if you want to use one specifically

class derived:public base1,public base2
{
public:
    using base1::start;
};
Aero answered 27/7, 2011 at 14:12 Comment(0)
P
4

Sure!

a.base1::start();

or

a.base2::start();
Pendentive answered 27/7, 2011 at 14:11 Comment(2)
Trying to understand - "if the inheritance were virtual, there would be no ambiguity". How is that?Castellated
@goldenmean: That hasn't been part of my answer for a while now.Pendentive
S
2

In addition to the answers above, if we are in the case of NON-VIRTUAL inheritance:

you can:

  1. use static_cast<base1*>(a).start()

or

  1. override start() in derived

Btw - please note the diamond problem that can appear. In this case you might want to use virtual.

Septillion answered 12/1, 2021 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.