61
Inheritance and Composition (aka containment) Textbook Chapter 14 • 14.1 – 14.4 1

Inheritance and Composition (aka containment) Textbook Chapter 14 14.1 – 14.4 1

Embed Size (px)

Citation preview

Inheritance and Composition (aka containment)

Textbook Chapter 14

• 14.1 – 14.4

1

2

Objectives

• 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

Objectives

• Become familiar with the C++ stream hierarchy

• Learn about containment

• Become familiar with the three basic principles of object-oriented design

4

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

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

Inheritance HierarchyAmong Vehicles

vehicle

wheeled vehicle boat

bicyclecar

four-door two-door

Every car is a wheeled vehicle.

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

• the class that inherits traits is the Derived Class

• the derived class is specialized by adding properties specific to it

8

Inheritance (continued)

• Single inheritance: derived class has a single base class– Multiple Inheritance possible but not used in CS215

• Can be viewed as a tree (hierarchy) where a base class is shown with its derived classes

9

10

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

11

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 members of the base class)

12

Base Class TimeType// 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 ;

} ;12

13

Class Interface Diagram

Private data:

hrs

mins

secs

Set

Increment

Write

Time

Time

TimeType class

14

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

15

Using Inheritance to Add Features #ifndef EXTTIME //Always have file guard#define EXTTIME// SPECIFICATION FILE ( exttime.h)#include “TimeType.h” //include the base class

class ExtTime : public TimeType // TimeType is the base class{public :

void Set ( int hours, int minutes, int seconds , string timeZone ) ;

void Write ( ) ; ExtTime ( int initHrs , int initMins , int initSecs ,

ZoneType initZone ) ; // constructor ExtTime ( ) ; // default constructor

private :string zone ; // added data member

} ;#endif // End of file: end file guard preprocessor if statement

16

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

17

Class Interface Diagram

Private data:

hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data:zone

18

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.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST cout << endl ;

18

19

ExtTime Implementation File

• Constructors defined

• All added public member functions defined

• All changed base class public member function defined (overridden)

• Destructor (if needed) defined

20

Start of Implementation File// exttime.cpp implementation file// Use includes// needed by any of the member functions#include<string> // strings used#include<iostream> // IO usedusing namespace std;// Always include header file of THIS CLASS// DO NOT INCLUDE BASE CLASS HEADER#include “exttime.h”

21

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

22

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

23

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” ;

}

24

Implementation of Another ExtTime Class Constructor

ExtTime :: ExtTime ( /* in */ int initHrs,

/* in */ int initMins,

/* in */ int initSecs,

/* in */ string initZone )

: TimeType (initHrs, initMins, initSecs) // base class constructor

// Precondition: 0 <= initHrs <= 23 && 0 <= initMins <= 59

// 0 <= initSecs <= 59 && initZone is assigned

// Postcondition:

// zone == initZone && Time set by base class constructor

{

zone = initZone ;

} 24

25

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

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

Implementation of ExtTime::Set function void ExtTime :: Set ( /* in */ int hours,

/* in */ int minutes,

/* in */ int seconds,

/* in */ string 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 ;

}27

28

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

{

TimeType :: Write ( ) ;

cout << ‘ ‘ << zone;

}28

29

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

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

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

• 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

33

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

34

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

35

36

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

37

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

38

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

39

Public Inheritance• 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

40

Public Inheritance

Base Member Type

Become This Type in Derived

Can be Accessed by Client?

Public Public Yes

Protected Protected N/A

Private N/A N/A

41

BasePrivateData

Overriding DerivedMembers

Client Code Derived Class

Overridden BaseMembers

Non-OverriddenBase MembersNon-Overridden

Base Members

BaseConstructors

DerivedConstructors

DerivedPrivateData

Call

Call

Base Class

42

Other Types of Inheritance• There are three types of inheritance

– Public

– Protected

– Private

• Different types treat base class information differently

• We will focus on Public Inheritance for CS215

43

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

44

Composition (or Containment)

• is a mechanism by which an object of one class contains an object of another class

• Called a “has-a” relationship

45

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 ; } ;

46

TimeCard ClassTimeCard has a TimeType object

Private data:

hrs

mins

secs

Punch

Private data:

id

timeStamp

Increment

SetPrint . . .

TimeCard

TimeCard

Write . . .

47

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 ;

} 47

48

Default Constructor

TimeCard :: TimeCard ( )

// Default constructor:

// timeStamp default constructor is called

{

id = 0;

}

49

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;}

50

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();

51

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

52

Two Programming Paradigms

Structural (Procedural) Object-Oriented PROGRAM (C) PROGRAM (C++)

FUNCTION

FUNCTION

FUNCTION

OBJECT

Operations

Data

OBJECT

Operations

Data

OBJECT

Operations

Data

53

Structured Programming

• Structured programming

– Function is a fundamental entity

– Debug functions

– Program is a collection of interacting functions

– Programmer is action-oriented

54

OOD and OOP

• OOD

– Object is a fundamental entity

– Debug objects

– Program is a collection of interacting objects

– Programmer is object-oriented

– OOD encourages code reuse

55

What is an object?

OBJECT

Operations

Data

set of methods(public member functions)

internal state(values of private data members)

56

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

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

58

Summary

• Derived class can redefine function members of a base class

– Redefinition applies only to objects (instances) of derived class

• Base class objects will still use the base class functionality.

59

Summary

• When initializing object of a derived class, the base class constructor is executed first

• A call to a base class constructor (with parameters) is specified in the heading of the definition of the derived class constructor

– When none is specified, the default is used

60

Summary

• In composition– Class member is an instance of another class– Call to constructor of member objects is

specified in heading of the definition of class’s constructor

61

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