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

Slides:



Advertisements
Similar presentations
Chapter 12: Inheritance and Composition
Advertisements

1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
1 class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Chapter 6 Object-Oriented Software Development.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Inheritance and Composition.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 12: Inheritance and Composition.
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Software Engineering Principles and C++ Classes
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 12: Inheritance and Composition.
Data Structures Using C++1 Chapter 1 Software Engineering Principles and C++ Classes.
1 Abstract Data Type (ADT) a data type whose properties (domain and operations) are specified (what) independently of any particular implementation (how)
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
1 Chapter 14-1 Object- Oriented Software Development Dale/Weems.
1 Chapter 14-2 Object- Oriented Software Development Dale/Weems.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 13: Inheritance and Composition.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Chapter 12: Adding Functionality to Your Classes.
Chapter 11: Inheritance and Composition. Objectives In this chapter, you will: – Learn about inheritance – Learn about derived and base classes – Redefine.
CMSC 202 Inheritance.
1 Chapter 14 Object-Oriented Software Development.
1 Chapter 14 Object- Oriented Software Development Dale/Weems.
Chapter 8 More Object Concepts
1 Chapter 14 Object-Oriented Software Development Dale/Weems/Headington.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Chapter 13: Inheritance and Composition
1 Chapter 14 Object-Oriented Software Development Dale/Weems.
Data Structures Using C++1 Chapter 1 -Software Engineering Principles -ADT and Classes.
Data Structures Using C++1 Chapter 1 Software Engineering Principles and C++ Classes.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Classes Structured Programming 256 Chapter 8 Classes - Part I OOP & Class Object Terminology File Management.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 12: Inheritance and Composition.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CS 132 Spring 2008 Chapter 2 Object-Oriented Design (OOD) and C++ Ideas: * Inheritance (and protected members of a class) ** Operator overloading Pointer.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Department of Computer Science Data Structures Using C++ 2E Chapter 2 Object-Oriented Design (OOD) and C++  Learn about inheritance  Learn about derived.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 13: Inheritance and Composition.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Another way to define a class Inheritance..!!. 2 Why Inheritance ? Inheritance is a mechanism for building class types from existing class types defining.
Chapter 11: Inheritance and Composition. Introduction Two common ways to relate two classes in a meaningful way are: – Inheritance (“is-a” relationship)
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance Concept Polygon Rectangle Triangle class Rectangle{
Inheritance CMSC 202, Version 4/02.
Lecture 13.
Object-Oriented Design (OOD) and C++
Polymorphism.
About the Presentations
Chapter Structured Types, Data Abstraction and Classes
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Introduction to Structured Data Types and Classes
CS212: Object Oriented Analysis and Design
Classes and Data Abstraction
Programming Techniques Course
Chapter 11: Inheritance and Composition
Chapter 14 Object-Oriented Software Development
Another way to define a class
Lecture 6: Polymorphism
Presentation transcript:

Inheritance and Composition (aka containment) Textbook Chapter –

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 Hierarchy Among Vehicles vehicle wheeled vehicleboat 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 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 Set Increment Write 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.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 // strings used #include // IO used using 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 Yes Protected N/A PrivateN/A

41 Base Private Data Overriding Derived Members Client Code Derived Class Overridden Base Members Non-Overridden Base Members Non-Overridden Base Members Base Constructors Derived Constructors Derived Private Data 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 Class TimeCard has a TimeType object Private data: hrs mins secs Punch Private data: id timeStamp Increment Set Print. 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 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