Lecture Preview: Inheritance

(Suggested book reading: Programming Abstractions in C++, section 4.4, Chapter 19)

(This is just a paraphrase/summary of the first 4 paragraphs of section 4.4, which you may wish to just read instead or in addition to this summary; it is a very quick and easy read.)

One benefit of Object-Oriented Programming (OOP) is encapsulation, which means grouping state (data) and behavior (functions/methods) together in a whole that makes sense and hides implementaton details. Another benefit of OOP is inheritance, which is the ability to create relationships between different objects where they inherit data and/or behavior from other objects.

Inheritance in computer science creates a relationship between two classes where an instance of one class is an instance of the other class as well. A common analogy for this is to look at the relationships between shapes that you learned as a kid: a square is a rectangle, which is a polygon. We could say that a square inherits from rectangle, and rectangle in turn inherits from polygon.

Biological taxonomies also closely match how we think about inheritance in computer science. Here is the example from your textbook (Figure 4-5):

inheritance example from biology

You've seen some examples of these relationships in class already: the stream classes for doing I/O in C++. An ifstream that you use to read input from a file is one kind of istream, which is a more general class for reading input (from files or from other sources). In class we'll see how to establish these relationships between different objects of our own in our code, and why it is useful to do so.

One really useful benefit you get when you use inheritance is called polymorphism. Polymorphism is when one piece of client code can interact with many different kinds of objects and get a different result depending upon which kind of object it is presently interacting with. For example, the following silly image shows an example of real-world polymorphism, where a person asks many different kinds of animals to "speak" and each kind of animal responds with different behavior that is specific to that kind of animal. We'll discuss how this works in C++ code during lecture.

polymorphism example

This document and its content are copyright © Marty Stepp, 2015. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the authors' expressed written permission.