Containment Delegation  «Prev  Next»
Lesson 2 Reusability and C++
Objective Explain how C++ reusability is a source code mechanism.

Reusability and C++

Reusing a component or C++ class is very desirable. Before we look at how one component reuses another, let's look at C++ reuse mechanisms .
For the sake of discussion, suppose we have access to a component called FindFile that knows how to search local or remote directories for a file. We would like to reuse FindFile to build a FileManager component that combines FindFile's functionality with additional services such as directory management and file viewing. A client using the FileManager component would not see the FindFile component, yet the functionality of FindFile is available through the FindManager component (directly or indirectly).

The functionality of FindFile is available through the FindManager component
The functionality of FindFile is available through the FindManager component

In the image above, FileManager's reuse of FindFile is not visible to the client. The client sees only FileManager. FileManager offers (directly or indirectly) the services provided by FindFile without exposing, to the client, that it is reusing FindFile.
In C++, we could directly instantiate FindFile's classes or derive classes from FindFile's classes to build a module that combines FindFile's services with other services. For either case, we need an include file that describes the internal layout of C++ classes in FindFile. Our integration with FindFile is at the source code level at development time. Clients using FileManager would instantiate classes in FileManager. They have access to FindFile's functionality through FileManager classes.

Clients using FileManager instantiate classes in FileManager and have access to FindFile's functionality through FileManager classes
Clients using FileManager instantiate classes in FileManager and have access to FindFile's functionality through FileManager classes

In the image above, FileManager reuses functionality from FindFile through inheritance. C++-style inheritance normally means we reuse code from base classes. This is often called implementation inheritance because, by instantiating a derived class, we inherit code and data from base classes. Code that uses a derived class can access public code and data in the base class directly through a variable or pointer to the derived class. Code within the derived class can access public and protected code within base classes.
The key point to take away from this lesson is that C++-style inheritance is a source-code-based reusability mechanism. FileManager needs the internal in-memory layout of classes in FindFile to derive a class from a class in FindFile.