1 / 85

C++ Programming: Program Design Including Data Structures, Second Edition

C++ Programming: Program Design Including Data Structures, Second Edition. Chapter 12: Inheritance and Composition. 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

donnel
Télécharger la présentation

C++ Programming: Program Design Including Data Structures, Second Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Programming: Program Design Including Data Structures, Second Edition Chapter 12: Inheritance and Composition

  2. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  3. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  4. OBJECT FUNCTION Operations Data FUNCTION OBJECT OBJECT Operations Data FUNCTION Operations Data Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM expanded by J. Goetz, 2004

  5. Object-Oriented Programming Language Features 1. Data abstraction 2. Inheritance of properties 3. Dynamic binding of operations to objects expanded by J. Goetz, 2004

  6. OOP TermsC++ Equivalents Object Class object or class instance Instance variable Private data member Method Public member function Message passing Function call ( to a publicmember function ) expanded by J. Goetz, 2004

  7. What is an object? OBJECT set of methods (public member functions) internal state (values of private data members) Operations Data expanded by J. Goetz, 2004

  8. vehicle wheeled vehicle boat car bicycle two-door four-door Inheritance Hierarchy Among Vehicles Every car is a wheeled vehicle. expanded by J. Goetz, 2004

  9. 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 expanded by J. Goetz, 2004

  10. Inheritance and Composition • The two common ways to relate two classes in a meaningful way are: • Inheritance (“is-a” relationship) • Composition (“has-a” relationship) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  11. 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  12. Inheritance (continued) • Single inheritance: derived class has a single base class • Multiple inheritance: derived class has > 1 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  13. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  14. Inheritance Facts • 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 (e.g. shape) can be inherited either • as public members or • class circle : public shape { }; • as private members by the derived class • class circle : private shape { }; // or equivalent • class circle : shape { }; // assume private C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  15. Inheritance (continued) 3. The derivedclass can include additional data and/or function members 4. Derived class can redefine public member functions of base class • Redefinitionapplies only to objects of the derived class, not to thebase class 5. Alldata/function membersof the base class are also data/function membersof the derived class C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  16. class Time Specification // SPECIFICATION FILE ( time.h ) class Time { public : void Set (int hours ,int minutes , int seconds ) ; void Increment ( ) ; void Write ( ) const ; Time ( int initHrs, int initMins, int initSecs ) ; //constructor Time () ; // default constructor private : int hrs ; int mins ; int secs ; } ; 16 expanded by J. Goetz, 2004

  17. Class Interface Diagram Timeclass Set Private data: hrs mins secs Increment Write Time Time expanded by J. Goetz, 2004

  18. Using Inheritance to Add Features // SPECIFICATION FILE ( exttime.h) #include “time.h” enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ; class ExtTime : public Time // Time is the base class { public : void Set (int hours, int minutes, int seconds , ZoneType timeZone ) ; void Write ( ) const ; ExtTime ( int initHrs , int initMins , int initSecs , ZoneType initZone ) ; // constructor ExtTime ( ) ;// default constructor private : ZoneType zone ; // added data member } ; 18 expanded by J. Goetz, 2004

  19. class ExtTime: public Time • says class Time is apublic 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 Setand Write are overridden expanded by J. Goetz, 2004

  20. Class Interface Diagram ExtTimeclass Set Set Private data: hrs mins secs Increment Increment Write Write ExtTime Time ExtTime Time Private data: zone expanded by J. Goetz, 2004

  21. Client Code UsingExtTime #include “exttime.h” . . . 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 ; 21 expanded by J. Goetz, 2004

  22. 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 ; } • at run time, the base class constructor is implicitly called first,before the body of the derived class’s constructor executes expanded by J. Goetz, 2004

  23. Implementation of ExtTime Class Constructor with parameters ExtTime :: ExtTime ( /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs, /* in */ ZoneType initZone ) : Time (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 ; } 23 // if the base class constructor requires parameters, they must be passed by the derived class’s constructor expanded by J. Goetz, 2004

  24. Implementation of ExtTime::Set function void ExtTime :: Set ( /* in */ int hours, /* in */ int minutes, /* in */ int seconds, /* in */ ZoneType time Zone ) // Precondition: 0 <= hours <= 23 && 0 <= minutes <= 59 // 0 <= seconds <= 59 && timeZone is assigned // Postcondition: // zone = timeZone && Time set by base class function { Time :: Set (hours, minutes, seconds); zone = timeZone ; } 24 expanded by J. Goetz, 2004

  25. Implementation of ExtTime::Write Function void ExtTime :: Write ( ) const // 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” } ; Time :: Write ( ) ; cout << ‘ ‘ << zoneString [zone] ; } 25 expanded by J. Goetz, 2004

  26. Redefining (Overriding) Member Functions of the Base Class • To redefine a public member function of a base class • Corresponding function in the derived classmust have the • same name, • number, and • types of parameters C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  27. Redefining (Overriding) Member Functions of the Base Class (continued) • If derived class overrides a public member function of thebase class, then to call the base class function, specify: • Name of the base class • Scope resolution operator (::) • Function name with the appropriate parameter list C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  28. Constructors of Derived and Base Classes • Derived class constructor cannot directly accessprivate 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 constructoris specified in the heading of derived class constructor definition ExtTime :: ExtTime (int initHrs, int initMins, int initSecs, ZoneType initZone ) : Time (initHrs, initMins, initSecs) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  29. 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 expanded by J. Goetz, 2004

  30. class rectangleType // rectangleType.h { public: void setDimension(double l, double w); //Function to set the length and width of the rectangle. //Postcondition: length = l; width = w; double getLength() const; //Function to return the length of the rectangle. //Postcondition: The value of length is returned. double getWidth() const; //Function to return the width of the rectangle. //Postcondition: The value of width is returned. double area() const; //Function to return the area of the rectangle. //Postcondition: The area of the rectangle is // calculated and returned. double perimeter() const; //Function to return the perimeter of the rectangle. //Postcondition: The perimeter of the rectangle is // calculated and returned. void print() const; //Function to output the length and width of //the rectangle. rectangleType(); //default constructor //Postcondition: length = 0; width = 0; rectangleType(double l, double w); //constructor with parameters //Postcondition: length = l; width = w; private: double length; double width; }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  31. double rectangleType::perimeter() const { return 2 * (length + width); } void rectangleType::print() const { cout << "Length = " << length << "; Width = " << width; } rectangleType::rectangleType(double l, double w) { setDimension(l, w); } rectangleType::rectangleType() //default constructor { length = 0; width = 0; } #include <iostream> // rectangleType.cpp #include "rectangleType.h" usingnamespace std; void rectangleType::setDimension(double l, double w) { if (l >= 0) length = l; else length = 0; if (w >= 0) width = w; else width = 0; } double rectangleType::getLength() const { return length; } double rectangleType::getWidth()const { return width; } double rectangleType::area() const { return length * width; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  32. class boxType: public rectangleType // boxType.h { public: void setDimension(double l, double w, double h); //Function to set the length, width, and height //of the box. //Postcondition: length = l; width = w; height = h; double getHeight() const; //Function to return the height of the box. //Postcondition: The value of height is returned. double area() const; //Function to return the surface area of the box. //Postcondition: The surface area of the box is // calculated and returned. double volume() const; //Function to return the volume of the box. //Postcondition: The volume of the box is // calculated and returned. void print() const; //Function to output the length and width of a rectangle. boxType(); //default constructor //Postcondition: length = 0; width = 0; height = 0; boxType(double l, double w, double h); //constructor with parameters //Postcondition: length = l; width = w; height = h; private: double height; }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  33. double boxType::volume() const { return rectangleType::area() * height; } void boxType::print() const { rectangleType::print(); cout << "; Height = " << height; } boxType::boxType() //default constructor { height = 0.0; } boxType::boxType(double l, double w, double h) : rectangleType(l, w) //constructor initializer { if(h >= 0) height = h; else height = 0; } #include <iostream> // boxType.cpp #include "rectangleType.h" #include "boxType.h" usingnamespace std; void boxType::setDimension(double l, double w, double h) { rectangleType::setDimension(l, w); if(h >= 0) height = h; else height = 0; } double boxType::getHeight() const { return height; } double boxType::area() const { return 2 * (getLength() * getWidth() + getLength() * height + getWidth() * height); } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  34. cout << "Line 19: myBox2: "; //Line 19 myBox2.print(); //Line 20 cout << endl; //Line 21 cout << "Line 22: Surface Area of myBox2: " << myBox2.area() << endl; //Line 22 cout << "Line 23: Volume of myBox2: " << myBox2.volume() << endl; //Line 23 return 0; //line 24 } #include "rectangleType.h" #include "boxType.h" usingnamespace std; int main() { rectangleType myRectangle1; //Line 1 rectangleType myRectangle2(8, 6); //Line 2 boxType myBox1; //Line 3 boxType myBox2(10, 7, 3); //Line 4 cout << fixed << showpoint << setprecision(2); //Line 5 cout << "Line 6: myRectangle1: "; //Line 6 myRectangle1.print(); //Line 7 cout << endl; //Line 8 cout << "Line 9: Area of myRectangle1: " << myRectangle1.area() << endl; //Line 9 cout << "Line 10: myRectangle2: "; //Line 10 myRectangle2.print(); //Line 11 cout << endl; //Line 12 cout << "Line 13: Area of myRectangle2: " << myRectangle2.area() << endl; //Line 13 cout << "Line 14: myBox1: "; //Line 14 myBox1.print(); //Line 15 cout << endl; //Line 16 cout << "Line 17: Surface Area of myBox1: " << myBox1.area() << endl; //Line 17 cout << "Line 18: Volume of myBox1: " << myBox1.volume() << endl; //Line 18 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  35. Header File of a Derived Class • To definenewclasses • Create new header files • To createnew classes based on previously defined classes • Header files of the new classes contain commands that refers to thebase classes #include "rectangleType.h" • The definitions of the member functions can be placed in a separate file "boxType.h“ • Use the preprocessor command (#include) to include a header file in a program • The preprocessor processes the program before it is compiled C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  36. Multiple Inclusions • To avoid multiple inclusion of a file in a program p.637 • 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  37. Multiple Inclusions • Use certain preprocessor commands in the header file (“file guard”) • 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 Example: Header file test.h #ifndef H_test #define H_test const int One = 1; const int Two = 2; #endif C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  38. ios is the base class for all stream classes • istreamand ostream are derived from ios • ifstreamis derived from istream • ofstreamis derived from the ostream • ios contains formatting flags and member functions to access/modify the flag settings C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  39. C++ Stream Classes (continued) • istream and ostream provideoperations for data transfer between memory and devices • istream defines the extraction operator (>>) and functions such as cin, get and ignore • ostream defines the insertion operator (<<), which is used by cout C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  40. C++ Stream Classes (continued) • ifstreamis derived from istream for fileinput • Objects of type ifstream are for fileinput • ofstream is derived from ostream forfile output • Objects of type ofstream are for file output • Header file fstreamcontains the definitions of ifstreamand ofstream C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  41. Protected Members of a Class • Private members of a class cannot be directly accessed outside the class • to give derived class access to a private member of a base class • 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  42. Public Inheritance class B : memberAccessSpecifier A { …}; If the memberAccessSpecifier ispublic, class B : public A { …}; then • Publicmembers of A (base) are publicmembers of B (derived) and can be directly accessedin class B • Protectedmembers of A are protectedmembers of B and can be directly accessedby the member functions (and friend functions) of B • Private members of A are hidden in B and can be accessed by member functions (and friend functions) of B through public or protected members of A C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  43. Protected Inheritance If the memberAccessSpecifier is protected, class B : protected A { …}; then • Publicmembers of A are protectedmembers of B and can be accessedby the member functions (and friend functions) of B • Protectedmembers of A are protected members of B and can be accessedby the member functions (and friend functions) of B • Private members of A are hidden in B and can be accessed bymember functions (and friend functions) of B through public or protected members of A C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  44. Private Inheritance If the memberAccessSpecifier is private, class B : private A { …}; then • Publicmembers of A are private members of B and can be accessedby the member functions (and friend functions) of B • Protectedmembers of A are private members of B and can be accessedby the member functions (and friend functions) of B • Private members of A are hidden in B and can be accessed bymember functions (and friend functions) of B through public or protected members of A C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  45. Inheritance as public, protected, or private • Public members of a base class can be inherited either as public, protected or private • Protected members of a base class can be inherited either as protected or private • Private members of a base class can be inherited either as private C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  46. Composition • In composition, >= member(s) of a class are/include objects of another class type • Composition is a “has-a” relation • Arguments to the constructor of a member-object are specified in the heading part of the definition of the constructor C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  47. Composition (continued) • Member-objects of a class are constructed • In theorderthey are declared • Not in the order they are listed in the constructor’s member initialization list • Before the enclosing class objects are constructed C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

  48. ATimeCard object has aTime object #include “time.h” class TimeCard { public: void Punch ( /* in */ int hours, /* in */ int minutes, /* in */ int seconds ) ; void Print ( ) const ; TimeCard ( /* in */ long idNum, /* in */ int initHrs, /* in */ int initMins, /* in */ int initSecs ) ; TimeCard ( ) ; private: long id ; Time timeStamp ; //member(s) of a class include // objects of another class type } ; expanded by J. Goetz, 2004

  49. Punch TimeCard Class TimeCardhas aTime object Private data: id timeStamp Print . . . Private data: hrs mins secs Set Increment Write . . . TimeCard TimeCard expanded by J. Goetz, 2004

  50. Implementation of TimeCard Class Constructor TimeCard :: TimeCard ( /* in */ long 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 ; } 50 expanded by J. Goetz, 2004

More Related