14: Inheritance & Composition
One of the most compelling
features about C++ is code
reuse. But to be revolutionary,
you need to be able to do a lot more than
copy code and change it.
That’s the C approach, and it
hasn’t worked very well. As with most everything in C++, the solution
revolves around the class. You reuse code by creating new classes, but instead
of creating them from scratch, you use existing classes that someone else has
built and debugged.
The trick is to use the classes without
soiling the existing code. In this chapter you’ll see two ways to
accomplish this. The first is quite straightforward: You simply create objects
of your existing class inside the new class. This is called composition
because the new class is composed of objects of existing
classes.
The second approach is subtler. You
create a new class as a type of an existing class. You literally take the
form of the existing class and add code to it, without modifying the existing
class. This magical act is called inheritance,
and most of the work is done by the compiler. Inheritance is one of the
cornerstones of object-oriented programming and has additional implications that
will be explored in Chapter 15.
It turns out that much of the syntax and
behavior are similar for both composition and inheritance (which makes sense;
they are both ways of making new types from existing types). In this chapter,
you’ll learn about these code reuse
mechanisms.
|