next up previous
Next: Use relationship Up: Specify Dependencies Previous: Inheritance relationship

Containment relationship

Where containment is uesd, there are two major alternatives for representing an object of a class X:

The following example demonstrates the basic usage of the different solutions:

class X
{
public:
    X(int);
    // ...
};

class C
{
    X	a;
    X  *p;
    X  &r;
public:
    C( int i, int j, int k) : a(i), p(new X(j)), r(*new X(k)) { /* ... */ }
   ~C() { delete p; delete &r; }
};

Member of type X is preferred, because of efficiency in space, time, and human effort. The pointer solution is useful when the contained object may vary in the life of of the container.

The inheritance hierarchy also expresses some kind of containtment. There is a (not easy) tradeoff to decide between membership versus inheritance.



Porkoláb Zoltán 2001-09-03