2.1 The problem

Consider the following class definitions:

 
1class A 
2{ 
3  // defns 
4  public
5    virtual void m1(void); 
6}
7 
8class B : public A 
9{ 
10  // defns 
11  public
12    virtual void m1(void); 
13};

Now, consider a function as follows:

 
14void f1(A p1) 
15{ 
16  // some code before 
17  p1.m1();  
18  // some code after 
19}

The last piece of the puzzle is a call to f1:

 
20void test(void
21{ 
22  B myB; 
23 
24  // code to modify myB 
25  f1(myB);  
26}

Line 25 is actually permitted because it involves a by-value up cast. It takes the object myB, and create a new object of class A from it. Because there is no explicit constructor of class A from a parameter of class B, the compiler generates code to only copy the A-specific data members to the newly created object, and that is passed by value to subroutine f1.

The problem is that the method m1 used on line 17 is only going to use the A::m1. This is because parameter p1 is an object of class A. Note that the use of virtual method does not matter in this case, because p1 is an object of class A, not a pointer to, or a reference of an object of class A.