6 Virtual methods

Virtual methods work the same way in the case of multiple inheritance as in the case of single inheritance. Let us examine the example in listing 5.


Listing 5:virtualmethod
 
1class A 
2{ 
3  public
4    virtual void m1(void{} 
5    void concreteA(void{ m1(); }  
6}
7 
8class B 
9{ 
10  public
11    virtual void m1(void{} 
12    void concreteB(void{ m1(); } 
13}
14 
15class C : public A, public B 
16{ 
17  public
18    virtual void m1(void{ A::m1(); B::m1(); } 
19}
20 
21void test(void
22{ 
23  C myC; 
24  A *pA = &myC; 
25  B *pB = &myC; 
26 
27  pA>m1();  
28  pA>concreteA();  
29  pB>m1();  
30  pB>concreteB();  
31}

In this case, both line 27 and line 29 invoke C::m1, which in return calls the m1 of both superclasses.

Note that line 28 ends up calling C::m1(), and line 30 ends up calling C::m1() as well.

This is because the invocation of line 5 is determined at run time.