4.1 Duplicating pointer behaviors

Our first task to make a WhereIs object act like a pointer to a ThisIsA object, but with the proper exposure of the actual payload type. This can be accomplished by the use class templates.

Our first attempt is illustrated by listing 1.


Listing 1:WhereIs.01
 
1class PayLoadType 
2{ 
3    int x; 
4  public: 
5    void setx(int v) { x = v; } 
6    int getx(void) { return x; } 
7}; 
8 
9 
10template <class T> 
11class WhereIs 
12{ 
13  // private section of WhereIs 
14    class ThisIsA 
15    { 
16      // private section of ThisIsA 
17        T payload; 
18      public: 
19        T &getPayload(void) { return payload; } 
20        ThisIsA(const T &original):payload(original) {} 
21        ThisIsA(void) {} 
22    }; 
23    ThisIsA *ptr; 
24  public: 
25    WhereIs(void):ptr(0) {} 
26    WhereIs(WhereIs<T> &other):ptr(other.ptr) {} 
27    T & operator*(void) { return ptr->getPayload(); } 
28    void nuke(void) { delete ptr; ptr = 0; } 
29    void allocate(void) { ptr = new ThisIsA; } 
30    void allocate(const T &original) { ptr = new ThisIsA(original); } 
31    void becomesAliasOf(WhereIs<T> &other) { ptr = other.ptr; } 
32}; 
33 
34void test(void) 
35{ 
36  WhereIs<PayLoadType> v,w; 
37  w.allocate(); 
38  (*w).setx(30); 
39  v.becomesAliasOf(w); 
40}

We define ThisIsA as a member class of WhereIs<T>. This is because we will be using WhereIs<T> more often. In fact, the member class ThisIsA is private, which means we do not have explicit access to the class! This implies that we cannot explicitly create objects of the type WhereIs<T>::ThisIsA.

All operations are WhereIs centric. Here is a short explanation of the methods of WhereIs:

The test subroutine illustrates how some of the methods are used.

This first trial is neat, but all it does is to introduce a lot of extra typing with no real benefit.