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!
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().
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.
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 ...
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.
a.base1::start(); a.base2::start();
or if you want to use one specifically
class derived:public base1,public base2 { public: using base1::start; };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With