Say I have three classes:
class X{}; class Y{}; class Both : public X, public Y {};
I mean to say I have two classes, and then a third class which extends both (multiple-inheritance).
Now say I have a function defined in another class:
void doIt(X *arg) { } void doIt(Y *arg) { }
and I call this function with an instance of both:
doIt(new Both());
This causes a compile-time error, stating that the function call is ambiguous.
What are the cases, besides this one, where the C++ compiler decides the call is ambiguous and throws an error, if any? How does the compiler determine what these cases are?
Simple: if it’s ambiguous, then the compiler gives you an error, forcing you to choose. In your snippet, you’ll get a different error, because the type of
new Both()is a pointer toBoth, whereas both overloads ofdoIt()accept their parameters by value (i.e. they do not accept pointers). If you changeddoIt()to take arguments of typesX*andY*respectively, the compiler would give you an error about the ambiguous function call.If you want to explicitly call one or the other, you cast the arguments appropriately: