Re: multiple inheritance
Sushrut Sardeshmukh wrote:
Can you please help me to understand why this code does not compile?
I expect foo() to be called from B as signature matches the call.
where as if i call ptr->foo(10) then C::foo(int i) should be called.
but it does not happen.
class B {
public:
void foo();
};
class C {
public:
void foo(int i);
};
class D:public C, public B {};
int main(int argc, char * argv[])
{
D *ptr = new D();
ptr ->foo();
You need to know the steps that a function call goes through. First it
does name lookup, and then it does overload resolution. So first of
all, if name lookup results in an ambiguity, it does not matter what
arguments you provide, the problem occurred before they came into play.
The rules for name lookup require that the results be unambiguous, and
that requires that when searching bases for the names, the set of names
that are found (B::foo(), and C::foo(int), in this case) must all be
found in sub-object base(s) of the same type. But B and C are
different types, so the name lookup fails due to the ambiguity. This
is covered pretty clearly in the standard section 10.2.
If you'd like a solution, then inside class D, do this:
using C::foo;
using B::foo;
Now name resolution considers those names both in the scope of D, and
so when you call foo on an object of type D, all the names are found in
the same type (D), and so it no longer encoungers the ambiguity.
Chris
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]