Lesson 2 | What is inheritance? |
Objective | Define inheritance and describe its advantages. |
Define Class Inheritance in C++
Inheritance is a powerful code reuse mechanism. Through inheritance, you can derive a new class from an already-existing class. In other words, the existing class can be added to or altered to create the derived class. This creates a hierarchy of related types that share code and interface. Many useful types are variants of one another, and it is frequently tedious to produce the same code for each.
A derived class inherits the description of the base class. The derived class can then be altered by adding members, modifying existing member functions, and modifying access privileges.
Inheritance allows a new class to be defined by extending or modifying one or more existing classes.
The new class is called a derived class and the existing class is its base class.
A derived class can itself serve as a base class for other derived classes, enabling us to build hierarchies of classes related by inheritance. Inheritance allows us to avoid reinventing the wheel: instead of having to define every class from scratch, we can use existing classes as foundations on which to build new classes.
Code Reuse
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 is the C approach, and it has not 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 will 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.
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).