3.2 Cloning

At run time, we may need to clone an object that is passed by pointer. This is illustrated in listing 2.


Listing 2:cloneme
 
1class A 
2{ 
3  public
4    virtual void m1(void); 
5}
6 
7class B : public A 
8{ 
9  public
10    virtual void m1(void); 
11}
12 
13void test(const A *pA) 
14{ 
15  A *pClone; 
16 
17  pClone = new A(*pA); 
18  // do something that modifies *pClone 
19  pA->m1(); 
20  // get rid of the clone when we are done 
21  delete pClone; 
22  // leaving *pA intact 
23}

However, we have a problem here. The creation of the object pointed to by pClone uses a regular cloning (copy) constructor. Because the type pointed to by pA is class A, we cannot use any other constructors. As a result, the resulting clone is a genuine class A object, but nothing more. Note that pA can point to an object of class B.

This means that when m1 is invoked, the clone invokes A::m1, even though pA->m1() would have invoked B::m1. There are very few, if any, cases that we want a clone to revert to a super close instead of the class of the original object.

Fortunately, there is a way to get around the limitations of the copy constructor method.