4 Ambiguous methods

Listing 3 is ambiguous because both superclasses define method m1.


Listing 3:ambiguousmethod
 
1class A 
2{ 
3  public
4    void m1(void{} 
5}
6 
7class B 
8{ 
9  public
10    void m1(void{} 
11}
12 
13class C : public A, public B 
14{ 
15  public
16}
17 
18void test(void
19{ 
20  C myC; 
21 
22  myC.m1();  
23}

However, in this case, we have to ways to resolve the ambiguity. First, we can change line 22 to the following:

myC.A::m1();

However, we can also choose a “default” method m1 in the definition of class C. We can change the definition of class C as follows:

 
1class C : public A, public B 
2{ 
3  public
4    A::m1; 
5};

This tells the compiler that when we refer to method m1 of a class C object, by default we refer to that of class A.

Note that with this default, we can still change the statement on line 22 to specify the method m1 or class B using the syntax myC.B::m1().