Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition.

Similar presentations


Presentation on theme: "C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition."— Presentation transcript:

1 C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition

2 C++ Programming: From Problem Analysis to Program Design, Second Edition2 Objectives In this chapter you 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

3 C++ Programming: From Problem Analysis to Program Design, Second Edition3 Objectives Become familiar with the C++ stream hierarchy Explore three types of inheritance: public, protected, and private Learn about composition Become familiar with the three basic principles of object-oriented design

4 C++ Programming: From Problem Analysis to Program Design, Second Edition4 Inheritance and Composition The two common ways to relate two classes in a meaningful way are: 1.Inheritance (“is-a” relationship) 2.Composition/Containment (“has-a” relationship)

5 C++ Programming: From Problem Analysis to Program Design, Second Edition5 Inheritance Inheritance is an “is-a” relationship For instance,“every employee is a person” Inheritance lets us create new classes from existing classes New classes are called the derived classes Existing classes are called the base classes Derived classes inherit the properties of the base classes

6 6 Inheritance Hierarchy Among Vehicles vehicle wheeled vehicleboat bicyclecar four-door two-door Every car is a wheeled vehicle.

7 7 Inheritance is a mechanism by which one class acquires (inherits) the properties (both data and operations) of another class the class being inherited from is the Base Class (Superclass) the class that inherits is the Derived Class (Subclass) the derived class is then specialized by adding properties specific to it

8 8 class TimeType Specification // SPECIFICATION FILE( timetype.h ) class TimeType { public : void Set ( int hours, int minutes, int seconds ) ; void Increment ( ) ; void Write ( ) const ; TimeType ( int initHrs, int initMins, int initSecs ) ; // constructor TimeType ( ) ; // default constructor private : int hrs ; int mins ; int secs ; } ; 8

9 9 Class Interface Diagram Private data: hrs mins secs Set Increment Write Time TimeType class

10 10 Using Inheritance to Add Features #ifndef EXTTIME //Always have file guard #define EXTTIME // SPECIFICATION FILE ( exttime.h) #include “TimeType.h” enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ; class ExtTime : public TimeType // Time is the base class { public : void Set ( int hours, int minutes, int seconds, ZoneType timeZone ) ; void Write ( ) ; ExtTime ( int initHrs, int initMins, int initSecs, ZoneType initZone ) ; // constructor ExtTime ( ) ; // default constructor private : ZoneType zone ; // added data member } ; #endif // End of file: end file guard preprocessor if statement 10

11 11 class ExtTime: public Time says class Time is a public base class of the derived class ExtTime as a result, all public members of Time (except constructors) are also public members of ExtTime in this example, new constructors are provided, new data member zone is added, and member functions Set and Write are overridden

12 12 Class Interface Diagram Private data: hrs mins secs ExtTime class Set Increment Write Time Set Increment Write ExtTime Private data: zone

13 13 Client Code Using ExtTime #include “exttime.h” // specification file of ExtTime class. ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called thatTime.Write( ) ; // outputs 00:00:00 EST cout << endl ; thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT cout << endl ; thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST cout << endl ; 13

14 C++ Programming: From Problem Analysis to Program Design, Second Edition14 ExtTime Implementation File Constructors defined All added public member functions defined All changed base class public member function defined Destructor (if needed) defined

15 C++ Programming: From Problem Analysis to Program Design, Second Edition15 Start of Implementation File // exttime.cpp implementation file // Put includes // needed by any of the member functions #include // strings used #include // IO used using namespace std; // Always include class header file // DO NOT INCLUDE BASE CLASS HEADER #include “exttime.h”

16 16 Constructor Rules for Derived Classes at run time, the base class constructor is implicitly called first, before the body of the derived class’s constructor executes if the base class constructor requires parameters, they must be passed by the derived class’s constructor

17 17 Implementation of ExtTime Default Constructor ExtTime :: ExtTime ( ) // Default Constructor Postcondition: // hrs == 0 && mins == 0 && secs == 0 // (via an implicit call to base class default constructor ) // && zone == EST { zone = EST ; }

18 18 Implementation of Another ExtTime Class Constructor ExtTime :: ExtTime ( /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs, /* in */ ZoneType initZone ) : TimeType (initHrs, initMins, initSecs) // constructor initializer // Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59 // 0 <= initSecs <= 59 && initZone is assigned // Postcondition: //zone == initZone && Time set by base class constructor { zone = initZone ; } 18

19 19 Implementation of ExtTime::Set function void ExtTime :: Set ( /* in */ int hours, /* in */ int minutes, /* in */ int seconds, /* in */ ZoneType timeZone ) // Precondition: 0 <= hours <= 23 && 0 <= minutes <= 59 // 0 <= seconds <= 59 && timeZone is assigned // Postcondition: //zone == timeZone && Time set by base class function { TimeType :: Set (hours, minutes, seconds); zone = timeZone ; } 19

20 20 Implementation of ExtTime::Write Function void ExtTime :: Write ( ) // Postcondition: //Time has been output in form HH:MM:SS ZZZ // where ZZZ is the time zone abbreviation { static string zoneString[8] = { “EST”, CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT” } ; TimeType :: Write ( ) ; cout << ‘ ‘ << zoneString [zone] ; } 20

21 C++ Programming: From Problem Analysis to Program Design, Second Edition21 Inheritance (continued) Single inheritance: derived class has a single base class Multiple inheritance: derived class has more than one base class Can be viewed as a tree (hierarchy) where a base class is shown with its derived classes Public inheritance: all public members of base class are inherited as public members by derived class

22

23 C++ Programming: From Problem Analysis to Program Design, Second Edition23 Inheritance (continued) Private members of the base class are private to the base class −Members of the derived class cannot directly access them Public members of a base class can be inherited either as public members or as private members by the derived class The derived class can include additional data and/or function members

24 C++ Programming: From Problem Analysis to Program Design, Second Edition24 Inheritance (continued) Derived class can redefine public member functions of base class Redefinition applies only to objects of the derived class, not to the base class All data/function members of the base class are also data/function members of the derived class (but can only be accessed via public member functions of the base class)

25 C++ Programming: From Problem Analysis to Program Design, Second Edition25 Redefining (Overriding) Member Functions of the Base Class To redefine a public member function of a base class −Corresponding function in the derived class must have the same name, number, and types of parameters

26 C++ Programming: From Problem Analysis to Program Design, Second Edition26 Redefining (Overriding) Member Functions of the Base Class (continued) If derived class overrides a public member function of the base class, then to call the base class function, specify: −Name of the base class −Scope resolution operator (::) −Function name with the appropriate parameter list

27 C++ Programming: From Problem Analysis to Program Design, Second Edition27 Constructors of Derived and Base Classes Derived class constructor cannot directly access private members of the base class Derived class can initialize private data members of the derived class When a derived object is declared −It must execute one of the base class constructors Call to the base class constructor is specified in the heading of derived class constructor definition

28 C++ Programming: From Problem Analysis to Program Design, Second Edition28 Header File of a Derived Class To define new classes −Create new header files To create new classes based on previously defined classes −Header files of the new classes contain commands that specify where to look for the definitions of the base classes The definitions of the member functions are placed in a separate implementation file

29 C++ Programming: From Problem Analysis to Program Design, Second Edition29 Class Files Each class (including derived classes used in inheritance) has: Its own specification (header -.h) file to define the class for users Its own implementation file (.cpp) of public member functions For a derived class, its implementation file only contains new public member functions or base functions that are redefined

30 C++ Programming: From Problem Analysis to Program Design, Second Edition30 Client Code Includes Class Definitions Use the preprocessor command (#include) to include a header file in a program for all classes that you will use If you use a derived class, you DO NOT have to include its base header file (unless you are also using its base class directly)

31 C++ Programming: From Problem Analysis to Program Design, Second Edition31 Implementation File (.cpp) Compiles If you are the developer of a class, you also compile its implementation file (.cpp) with your program If you are using a class developed by someone else (string class, iostream class) they provide the compiled code of its implementation file for you (called an object module.o)

32 C++ Programming: From Problem Analysis to Program Design, Second Edition32 Including Class Definitions Use the preprocessor command (#include) to include a header file in a program for all classes that you will use The preprocessor processes the program before it is compiled and includes these files To avoid multiple inclusion of a file in a program −Use certain preprocessor commands in the header file (“file guard”)

33 33 often several program files use the same header file containing typedef statements, constants, or class type declarations--but, it is a compile-time error to define the same identifier twice this preprocessor directive syntax is used to avoid the compilation error that would otherwise occur from multiple uses of #include for the same header file #ifndef Preprocessor_Identifier #define Preprocessor_Identifier. #endif Avoiding Multiple Inclusion of Header Files

34 34 Example Using Preprocessor Directive #ifndef // timetype.h FOR COMPILATION THE CLASS DECLARATION IN // SPECIFICATION FILE FILE timetype.h WILL BE INCLUDED ONLY ONCE #ifndef TIME_H // Make this a different name than the class #define TIME_H // case sensitive - you can uppercase the class name class TimeType { public:... private:... } ; #endif

35 C++ Programming: From Problem Analysis to Program Design, Second Edition35 Using File Guards Are Required For user developed classes (like your own) that are not derived classes, no one else will be using them, and you can get away with not using these “file guards” For inherited classes, you will get errors if you do not use file guards FROM NOW ON YOU ARE REQUIRED TO USE THEM FOR ALL YOUR HEADER FILES

36 C++ Programming: From Problem Analysis to Program Design, Second Edition36 Inheritance Example: C++ Stream Classes ios is the base class for all stream classes istream and ostream are derived from ios ifstream is derived from istream ofstream is derived from the ostream ios contains formatting flags and member functions to access/modify the flag settings

37

38 C++ Programming: From Problem Analysis to Program Design, Second Edition38 C++ Stream Classes (continued) istream and ostream provide operations for data transfer between memory and devices istream defines the extraction operator (>>) and functions such as get and ignore ostream defines the insertion operator (<<), which is used by cout

39 C++ Programming: From Problem Analysis to Program Design, Second Edition39 C++ Stream Classes (continued) ifstream is derived from istream for file input ofstream is derived from ostream for file output Objects of type ifstream are for file input Objects of type ofstream are for file output Header file fstream contains the definitions of ifstream and ofstream

40 C++ Programming: From Problem Analysis to Program Design, Second Edition40 Protected Members of a Class Private members of a class cannot be directly accessed outside the class For a base class to give derived class access to a private member −Declare that member as protected The accessibility of a protected member of a class is in between public and private A derived class can directly access the protected member of the base class

41 C++ Programming: From Problem Analysis to Program Design, Second Edition41 Public Inheritance If the memberAccessSpecifier is public, then Public members of A (base) are public members of B (derived) and can be directly accessed in class B Protected members of A are protected members of B and can be directly accessed by the member functions of B Private members of A are hidden in B and can be accessed by member functions of B through public or protected members of A

42 C++ Programming: From Problem Analysis to Program Design, Second Edition42 Protected Inheritance If the memberAccessSpecifier is protected, then Public members of A are protected members of B and can be accessed by the member functions of B Protected members of A are protected members of B and can be accessed by the member functions of B Private members of A are hidden in B and can be accessed by member functions of B through public or protected members of A

43 C++ Programming: From Problem Analysis to Program Design, Second Edition43 Private Inheritance If the memberAccessSpecifier is private, then Public members of A are private members of B and can be accessed by member functions of B Protected members of A are private members of B and can be accessed by member functions of B Private members of A are hidden in B and can be accessed by member functions of B through the public or protected members of A

44 C++ Programming: From Problem Analysis to Program Design, Second Edition44 Public – Private - Protected Access to items of the base class: Client Derived class Public Yes Yes Private No No Protected No Yes No: Can only access via public member functions

45 C++ Programming: From Problem Analysis to Program Design, Second Edition45 Why Use Inheritance? Inheritance is used quite frequently: It saves coding: you only have to add or redefine the public member functions unique for your class It helps organize and simplify large programs The client doesn’t have to know anything about the hierarchy – just uses the derived class

46 46 Composition (or Containment) is a mechanism by which an object of one class contains an object of another class Called a “has-a” relationship

47 47 A TimeCard object has a Time object #include “TimeType.h” class TimeCard { public: void Punch ( /* in */ int hours, /* in */ int minutes, /* in */ int seconds ) ; void Print ( ) ; TimeCard ( /* in */ int idNum, /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs ) ; TimeCard ( ) ; private: long id ; TimeType timeStamp ; } ;

48 48 TimeCard Class TimeCard has a TimeType object Private data: hrs mins secs Punch Private data: id timeStamp Increment Set Print. TimeCard Write.

49 49 TimeCard Constructor TimeCard :: TimeCard ( /* in */ int idNum, /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs ) : timeStamp (initHrs, initMins, initSecs) // constructor initializer // Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59 // 0 <= initSecs <= 59 && initNum is assigned // Postcondition: //id == idNum && timeStamp set by its constructor { id = idNum ; } 49

50 C++ Programming: From Problem Analysis to Program Design, Second Edition50 Default Constructor TimeCard :: TimeCard ( ) // Default constructor: // timeStamp default constructor is called { id = 0; }

51 C++ Programming: From Problem Analysis to Program Design, Second Edition51 Punch Print Member Functions void TimeCard::Punch (int hrs, int min, int sec) { timeStamp.Set(hrs, min, sec); } void TimeCard::Print() { cout << "For ID: " << id << endl; cout << "Timestamp is: "; timeStamp.Write(); cout << endl; }

52 C++ Programming: From Problem Analysis to Program Design, Second Edition52 Sample Client Code cout << "Enter employee 1 ID: "; cin >> empID1; cout << endl; TimeCard timeCard1(empID1, 8, 1, 2); TimeCard timeCard2; timeCard1.Print(); timeCard2.Print(); timeCard2.Punch(9,3,4); timeCard2.Print();

53 53 Order in Which Constructors are Executed Given a class X, if X is a derived class its base class constructor is executed first next, constructors for member objects (if any) are executed (using their own default constructors if none is specified) finally, the body of X’s constructor is executed

54 54 Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM (C) PROGRAM (C++) FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT Operations Data

55 55 What is an object? OBJECT Operations Data set of methods (public member functions) internal state (values of private data members)

56 C++ Programming: From Problem Analysis to Program Design, Second Edition56 OOD and OOP The fundamental principles of Object-Oriented Design (OOD) are: −Encapsulation: combine data and operations on data in a single unit −Inheritance: create new objects from existing objects −Polymorphism: the ability to use the same expression to denote different operations

57 C++ Programming: From Problem Analysis to Program Design, Second Edition57 OOD and OOP (continued) OOD −Object is a fundamental entity −Debug objects −Program is a collection of interacting objects −Programmer is object-oriented −OOD encourages code reuse

58 C++ Programming: From Problem Analysis to Program Design, Second Edition58 OOD and OOP (continued) Structured programming −Function is a fundamental entity −Debug functions −Program is a collection of interacting functions −Programmer is action-oriented

59 C++ Programming: From Problem Analysis to Program Design, Second Edition59 OOD and OOP (continued) Object-oriented programming (OOP) implements OOD C++ supports OOP through the use of classes Polymorphic function or operator has many forms Function name and operators can be overloaded

60 C++ Programming: From Problem Analysis to Program Design, Second Edition60 OOD and OOP (continued) Every object has an internal state and an external interface Private data form the internal state Public member functions are the external interface Only the object can manipulate its internal state

61 C++ Programming: From Problem Analysis to Program Design, Second Edition61 Classes, Objects, & Operations Finding classes: begin with a problem description and identify all nouns and verbs From the list of nouns choose the classes From the list of verbs choose the operations (public member functions) Suppose we want to write a program that calculates and prints the volume and surface area of a cylinder

62 C++ Programming: From Problem Analysis to Program Design, Second Edition62 Classes, Objects, & Operations (continued) We can state this problem as follows: −Write a program to input the dimensions of a cylinder and calculate and print the surface area and volume −The nouns are bold and the verbs are italic −From the list of nouns we visualize a cylinder as a class (cylinderType) from which we can create many cylinder objects of various dimensions

63 C++ Programming: From Problem Analysis to Program Design, Second Edition63 Classes, Objects, & Operations (continued) The nouns (dimensions, surface area, and volume) are characteristics of a cylinder After identifying a class, determine three pieces of information about its objects: −Operations that an object can perform −Operations that can be performed on an object −Information that an object must maintain

64 C++ Programming: From Problem Analysis to Program Design, Second Edition64 Classes, Objects, & Operations (continued) From the verbs, choose a list of possible operations that an object of that class can perform, or have performed, on itself For the cylinderType class the possible operations are −Input, calculate, and print −Dimensions represent the data

65 C++ Programming: From Problem Analysis to Program Design, Second Edition65 Classes, Objects, & Operations (continued) The center of the base, radius of the base, and height of the cylinder are the characteristics of the dimensions Calculate: determine the volume and the surface area You can deduce the operations: cylinderVolume and cylinderSurfaceArea Print: display the volume and the surface area on an output device

66 C++ Programming: From Problem Analysis to Program Design, Second Edition66 Classes, Objects, & Operations (continued) Identifying classes via the nouns and verbs from the descriptions to the problem is not the only technique possible There are several other OOD techniques in the literature

67 C++ Programming: From Problem Analysis to Program Design, Second Edition67 Programming Example This programming example illustrates the concepts of inheritance and composition Problem: The mid-semester point at your local university is approaching −The registrar’s office wants to prepare the grade reports as soon as the students’ grades are recorded

68 C++ Programming: From Problem Analysis to Program Design, Second Edition68 Programming Example (continued) Some of the students enrolled have not yet paid their tuition −If a student has paid the tuition, the grades are shown on the grade report together with the grade-point average (GPA) −If a student has not paid the tuition, the grades are not printed Grade report indicates that grades have been held for nonpayment of the tuition Grade report also shows the billing amount

69 C++ Programming: From Problem Analysis to Program Design, Second Edition69 The Data File Data are stored in a file in the following form: 15000 345 studentName studentID isTuitionPaid numberOfCourses courseName courseNumber creditHours grade. studentName studentID isTuitionPaid numberOfCourses courseName courseNumber creditHours grade.

70 C++ Programming: From Problem Analysis to Program Design, Second Edition70 The Data File (continued) The first line indicates number of students enrolled and tuition rate per credit hour Students’ data is given thereafter A sample-input file is: 3 345 Lisa Miller 890238 Y 4 Mathematics MTH345 4 A Physics PHY357 3 B ComputerSci CSC478 3 B History HIS356 3 A.

71 C++ Programming: From Problem Analysis to Program Design, Second Edition71 Output Sample output for each student: Student Name: Lisa Miller Student ID: 890238 Number of courses enrolled: 4 Course No Course Name Credits Grade CSC478ComputerSci3B HIS356History3A MTH345 Mathematics4A PHY357Physics3B Total number of credits: 13 Mid-Semester GPA: 3.54

72 C++ Programming: From Problem Analysis to Program Design, Second Edition72 Input and Output Input: file containing data in the form given above Assume that the name of the input file is "stData.txt" Output: a file containing output of the form given above

73 C++ Programming: From Problem Analysis to Program Design, Second Edition73 Problem Analysis Two main components are: Course −Main characteristics of a course are: course name, course number, and number of credit hours Student −Main characteristics of a student are: student name, student ID, number of courses enrolled, name courses, and grade for each course

74 C++ Programming: From Problem Analysis to Program Design, Second Edition74 Problem Analysis (continued) −Operations on an object of the course type are: 1.Set the course information 2.Print the course information 3.Show the credit hours 4.Show the course number

75

76 C++ Programming: From Problem Analysis to Program Design, Second Edition76 Algorithm Design The basic operations to be performed on an object of the type studentType: 1.Set student information 2.Print student information 3.Calculate number of credit hours taken 4.Calculate GPA 5.Calculate billing amount 6.Sort courses according to course number

77

78 C++ Programming: From Problem Analysis to Program Design, Second Edition78 Main Program 1.Declare variables 2.Open input file 3.If input file does not exist, exit program 4.Open output file 5.Get number of students registered and tuition rate 6.Load students’ data 7.Print grade reports

79 C++ Programming: From Problem Analysis to Program Design, Second Edition79 Summary Inheritance and composition are meaningful ways to relate two or more classes Inheritance is an “is-a” relation Composition is a “has-a” relation Single inheritance: a derived class is derived from one class, called the base class Multiple inheritance: a derived class is derived from more than one base class

80 C++ Programming: From Problem Analysis to Program Design, Second Edition80 Summary Private members of a base class are private to the base class Public members of a base class can be inherited either as public or private Derived class can redefine function members of a base class −Redefinition applies only to objects of derived class

81 C++ Programming: From Problem Analysis to Program Design, Second Edition81 Summary A call to a base class constructor (with parameters) is specified in the heading of the definition of the derived class constructor When initializing object of a derived class, the base class constructor is executed first In composition −Class member is an object of another class −Call to constructor of member objects is specified in heading of the definition of class’s constructor

82 C++ Programming: From Problem Analysis to Program Design, Second Edition82 Summary Three basic principles of OOD are −Encapsulation −Inheritance −Polymorphism Finding classes: describe the problem and choose classes from the list of nouns and operations from the list of verbs


Download ppt "C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition."

Similar presentations


Ads by Google