Implementing Reusability

Our final topic involving sample code is reusability through both containment and aggregation. The Reuse sample (CHAP02\REUSE) demonstrates both techniques, using the Animal and Koala objects seen earlier. The KoalaC object in this sample implements its IAnimal interface through containment of the Animal object; KoalaA obtains IAnimal through aggregation. The same implementation of the Animal object is used in both cases; it was written to support either mechanism. Let's look first at how both Koala objects set up their relationships with Animal through the creation function CreateAnimal (found in ANIMAL.CPP). Then we'll look deeper into Animal's code to see how an object specifically supports aggregation. All of these objects use interface implementations to support multiple interfaces (even Animal, because as an aggregatable object it needs an explicit IUnknown).

Like the other samples we've seen, Reuse creates a small window with a menu through which you can create either Koala object and invoke the member functions of both interfaces. None of the member functions other than those in IUnknown actually do anything except return NOERROR, so again it is instructive to walk through this sample in a debugger. You will notice in the code that the various interface implementation classes are given a suffix to differentiate them from the various objects. This is to avoid linker errors with same-named classes.