C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 12 Inheritance and Composition At a Glance Instructor’s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms 12-1 C++ Programming: Program Design Including Data Structures, Fourth Edition 12-2 Lecture Notes Overview Chapter 12 discusses additional techniques of programming with classes. Classes provide reusability through their various relationships with each other. In this chapter, students are introduced to two means of relating classes: inheritance (an “is-a” relationship) and composition (a “has-a” relationship). They will also learn about the three basic principles of object-oriented design: encapsulation, inheritance, and polymorphism. Objectives In this chapter, the student will: Learn about inheritance Learn about derived and base classes Explore how to redefine the member functions of a base class Examine how the constructors of base and derived classes work Learn how to construct the header file of a derived class Explore three types of inheritance: public, protected, and private Learn about composition Become familiar with the three basic principles of object-oriented design Teaching Tips Inheritance 1. Explain why programmers might choose to extend a class definition when designing a new class, rather than write one from scratch. Teaching Tip Inheritance is one of the primary aspects of OOD; therefore, you might want to provide some additional real-world examples before continuing the discussion of this section. For example, demonstrate how a transportation class can be a base class from which many different modes might be derived, such as a bike, car, or plane. 2. Examine how the personType class from Chapter 11 can be extended to create a partTimeEmployee class. C++ Programming: Program Design Including Data Structures, Fourth Edition Teaching Tip 12-3 Discuss why extending the personType class is a better solution than simply writing another partTimeEmployee class and copying in the variables you need to use. Emphasize that this is a small example, but that many applications have large amounts of code that might be reused. Talk about the testing process for large applications and how reusable code might make the development of new applications more efficient and less prone to errors. 3. Discuss how the clockType class can be extended to provide additional capabilities such as time zone information. 4. Define the terms derived class and base class. 5. Define single and multiple inheritance. Use Figure 12-1 to illustrate the structure of a single inheritance hierarchy. Teaching Tip Note that not all object-oriented programming languages offer multiple inheritance. The reasons for this will be explored when multiple inheritance is discussed. 6. Examine the syntax for declaring a derived class. Illustrate with the shape and circle classes in Example 12-1. 7. Discuss the rules regarding derived class definitions in C++. Emphasize how issues of access are handled between base and derived classes with the private and public member access specifiers. Redefining (Overriding) Member Functions of the Base Class 1. Define the term overriding. 2. Explain how to override a function of a base class in a derived class. Teaching Tip Students may be unclear of the difference between overriding and overloading. Explain that a derived class member function overrides a base class function if it has the same name and parameter lists. However, if the derived class member function has differing parameter lists, it is not overriding the base function, but is overloading the inherited function in the derived class. 3. Examine the rectangleType and boxType classes presented in this section and describe how overriding takes place in some of the member functions. C++ Programming: Program Design Including Data Structures, Fourth Edition 12-4 4. Explain how to call a base member function from a derived class under various circumstances. Discuss the situations in which this is useful with the code presented in this section. Constructors of Derived and Base Classes 1. Explore the issues involved with executing a base class constructor from a derived class. 2. Examine the syntax for executing a default base class constructor from a derived class. 3. Examine the syntax for executing base class constructors with parameters from a derived class. 4. Illustrate how the constructors for derived and base classes work together using Example 12-2. Teaching Tip Verify that students are comfortable with the syntax for calling base constructors from a derived class constructor. Walk through each component of the boxType constructor with parameters to clarify. 5. Step through Example 12-3 and Figure 12-5 to illustrate how base and derived classes are used in a program. 6. Explain how to create header files for derived classes. Multiple Inclusions of a Header File 1. Examine how to use the ifndef, define, and endif preprocessor commands to avoid compiler errors when including a header file in more than one file in a program. Teaching Tip Explain why multiple inclusions of a header file can generate compiler errors. Note that programmers often place the entire header file between the ifndef/define and endif commands to avoid any errors. C++ Stream Classes 1. Describe how C++ stream classes are implemented using the inheritance mechanism with Figure 12-6. Protected Members of a Class 1. Explain when to declare the members of a base class as protected. C++ Programming: Program Design Including Data Structures, Fourth Edition 12-5 Inheritance as public, protected, or private 1. Step through the general rules for accessing public, protected, and private base classes. Teaching Tip Reiterate the importance of information hiding from the client. Ask students to discuss how the protected member access specifier assists in information hiding. 2. Illustrate how a derived class can directly access a protected member of a base class using Example 12-4. Quick Quiz 1 1. ____________________ represents an “is-a” relationship. Answer: Inheritance 2. Classes that are created from existing classes are called ____________________ classes. Answer: derived 3. True or False: A derived class object can directly access the private members of a base class. Answer: False 4. True or False: A derived class can have a constructor with default parameters. Answer: True Composition 1. Explain the “has-a” relationship between classes, where one or more members of a class are objects of another class. 2. Illustrate composition by showing how the dateType class presented in this section is an object in the personalInfo class. Illustrate with the UML diagram in Figure 12-8 and the accompanying code. Teaching Tip Note the differences in how class constructors are used in inheritance and composition relationships. In inheritance, the base class constructor is invoked with the class name, whereas in composition, the member object name is used to call its own constructor. C++ Programming: Program Design Including Data Structures, Fourth Edition 12-6 Object-Oriented Design (OOD) and Object-Oriented Programming (OOP) 1. Describe the limitations of structured programming. Teaching Tip Spend some additional time discussing the differences between OOP and structured programming to solidify the students’ understanding of both of these programming techniques. 2. Define the three basic principles of object-oriented programming: encapsulation, inheritance, and polymorphism. Teaching Tip Review examples of the above principles in action with the C++ library classes, functions, and operators that the students have studied thus far. 3. Introduce the concept of parametric polymorphism. Note that this will be discussed in more detail in a later chapter. 4. Briefly review the history of object-oriented programming. Identifying Classes, Objects, and Operations 1. Describe the technique of using nouns and verbs to identify classes and objects in a problem. Illustrate with the problem statement in this section. 2. Encourage students to work through the “Grade Report” Programming Example to consolidate their understanding of inheritance and composition. Quick Quiz 2 1. What is meant by the term encapsulation? Answer: Encapsulation is the ability to combine data, and the operations on that data, in a single unit. 2. ____________________ is the ability to use the same expression to denote different operations. Answer: Polymorphism 3. Objects interact with each other via ____________________. Answer: function calls 4. True or False: In structured programming, the function is a fundamental entity. Answer: True C++ Programming: Program Design Including Data Structures, Fourth Edition 12-7 Class Discussion Topics 1. Ask students to consider relevant issues when determining whether to use protected or private members in a base class. Are there any risks involved with using the protected member access specifier instead of the private member access specifier? 2. Note that many facets of object-oriented programming and structured programming overlap. Ask students to think of previous programming examples in which OOP and structured programming are both used (e.g., overloading the get function). Additional Projects 1. Rewrite the birthday program you created in Chapter 11 to use the personalInfo class presented in this chapter as a base class. You will extend the personalInfo class to include an array of gift objects. The gift class should contain a string for the gift, a string for where to buy the gift (either a URL or a store name), and an approximate price for the gift. Create separate header and implementation files for all of your classes, and write a short program to test them. 2. Create a group of related classes that represents the food pyramid advocated by current health experts. You can find a sample guide here: www.mypyramid.gov/. Design a simple inheritance hierarchy that has a base class named foodType. The base class has a variable for the name of the object, a variable for the calories of the object (given to the constructor as a parameter), and accessor and mutator functions for each. The derived classes will be the various food groups in the pyramid. Each derived class includes a const variable that indicates how many servings per day of that food group should be consumed. Include appropriate constructors, accessor and mutator functions, and a Boolean function that takes a number of servings and returns a message indicating whether it is within the acceptable range. Test your classes with a user program that declares and manipulates objects of every food group. Additional Resources 1. Learn about C++ Classes and Objects: Learn about Inheritance and Polymorphism: http://cplus.about.com/od/learning1/ss/cppobjects_5.htm 2. Object composition: http://en.wikipedia.org/wiki/Object_composition 3. Overriding in Object-Oriented Programming: www.codersource.net/cpp_overriding.html 4. Polymorphism: www.cplusplus.com/doc/tutorial/polymorphism.html C++ Programming: Program Design Including Data Structures, Fourth Edition 12-8 Key Terms Base classes: classes from which you derive new classes Composition: where one or more members of a class are objects of another class type; a “has-a” relationship Derived classes: new classes that we create from base classes Encapsulation: ability to combine data, and operations on that data, in a single unit Inheritance: ability to create new classes from existing classes; an “is-a” relationship Multiple inheritance: derived class is derived from more than one base class Polymorphism: ability to use the same expression to denote different operations Single inheritance: an object is derived from a single class Structured programming: top-down approach to programming, where problems were broken into modules, and each module solved a particular part of the problem