3.3 Virtual clone method

Although a constructor cannot be virtual, a cloning method can be virtual. Let us consider the example in listing 3.


Listing 3:virtualclone
 
1class A 
2{ 
3  public
4    virtual A *clone(); 
5    virtual void m1(void{ cout << ”A::m1” << endl; } 
6}
7 
8class B : public A 
9{ 
10  public
11    virtual A *clone(); 
12    virtual void m1(void{ cout << ”B::m1” << endl; } 
13}
14 
15*A::clone() 
16{ 
17  return new A(*this); 
18} 
19 
20*B::clone()  
21{ 
22  return new B(*this); 
23}

In this example, line 20 starts the definition of a overriden virtual cloning function. Note that there is no explicit cast. This is because it is a method of class B, so we know exactly the type of this is (B *). The return value is not explicitly casted because the compiler can handle an implicit static up cast.

With the class definitions in listing 3, we can test it with the code in listing 4.


Listing 4:usevirtualclone
 
24void test(void
25{ 
26  A myA; 
27  B myB; 
28  A *pA1, *pA2; 
29 
30  pA1 = &myA; 
31  pA2 = pA1->clone(); 
32  pA2->m1(); 
33  delete pA2; 
34  pA1 = &myB; 
35  pA2 = pA1->clone(); 
36  pA2->m1(); 
37  delete pA2; 
38}

The output of listing 4 is "A::m1", followed by "B::m1".