4.4. Composition and delegation

We say that ClassB is composed with ClassA if ClassB has a ClassA or ClassA* member; for short we can say ClassB has a ClassA. And, as before, ClassB inherits from ClassA if ClassB is derived from ClassA as a child class; for short we say ClassB is a ClassA.

As it turns out, you can always replace an inheritance relationship by a composition relationship as indicated in Figure 4.7. If ClassB has a ClassA member object *_pA, then (a) a ClassB object gets a set of ClassA data fields wrapped up inside *_pA and, (b) ClassB can implement the same methods as ClassA simply by passing these method calls off to *_pA. When you pass method calls to a composed object, this is called delegation.

Figure 4.7. Inheritance and ...

Get Software Engineering and Computer Games now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.