27
11/24/08 MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Overriding Theme of OO Design and Programming: Programming: reuse existing code while growing/specializing the application by adding new functionality in a systematic, consistent way that keeps program readable . . Main Idea for Implementation: Main Idea for Implementation: Existing class is extended to a new Existing class is extended to a new class class Base class Derived class inherits data members and functions of the base class, i.e. has all attributes of and therefore is a special case of the base class. The relationship between derived and base class is known as the "is-a" relationship + • defines new is-a

11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

  • View
    220

  • Download
    1

Embed Size (px)

Citation preview

Page 1: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

1

10. Inheritance - Reusing and Augmenting CodeOverriding Theme of OO Design and Programming: Overriding Theme of OO Design and Programming: • reuse existing code while• growing/specializing the application by adding new

functionality in a • systematic, consistent way that keeps program readable..

Main Idea for Implementation:Main Idea for Implementation:

Existing class is extended to a new classExisting class is extended to a new class

Base class Derived class• inherits data members and functions of the base class, i.e. has all attributes of and therefore is a special case of the base class. The relationship between derived and base class is known as the "is-a" relationship

+• defines new data/functions or modifies existing ones

is-a

Page 2: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

2

Base and Derived Classes - ExamplesBase and Derived Classes - Examples

is-a

2D_Shape Rectangleis-a

Note:Note: Square inherits directly from Rectangle (direct base class) and indirectly from 2D_Shape (indirect base class).

Case Study:Case Study:

String BCStringis-a

the user defined class from previous lecturewith no bound checks

String extended with Bound-Checking (BC) ability (P&L, Ch.10)

Rectangle Squareis-a

Base class Derived class

Page 3: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

3

Implementing Inheritance: Basic Questions on the Implementing Inheritance: Basic Questions on the Relationship between Base and Derived ClassesRelationship between Base and Derived Classes

1. Do derived class objects have access to private data of the base class?

2. Do the inherited members and methods of the base class retain their access type (public/private/protected) in the derived class? If not, how does the access change?

3. Does the derived class inherit all members and methods of the base class? If yes, what happens when the base class methods do not make sense for the derived class objects?

4. Can derived class objects be treated as base class objects? And vice versa: Can base class objects be treated as derived class objects?

Page 4: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

4

Implementing Inheritance: Basic Questions on the Implementing Inheritance: Basic Questions on the Relationship between Base and Derived Classes (continued)Relationship between Base and Derived Classes (continued)

5. How can we reuse the code of base class methods while modifying them to suit/ take into account the new attributes of the derived class.

6. Do we need new constructors and destructor for the derived class? If yes, how do constructors/destructor of the derived class relate to the ones of the base class?

7. Do we need new assignment operators for the derived class? If yes, how do assignment operators of the derived class relate to the ones of the base class?

I will now discuss each one of these questions in more detail and illustrate the solutions on code segments from the case study implementation of the BCString class derived from the String base class.

Page 5: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

5

1. Private members of the base class are inaccessible for 1. Private members of the base class are inaccessible for derived class objectsderived class objects

1. Do derived class objects have access to private data of the base class?

No, they do not. If we allow access from a derived to a base class, we automatically allow access from a derived class of the derived class to the base class as well, thus practically destroying the encapsulation principle.

But if the derived class inherits the private members of the base class are they not private members of the derived class as well, and thus accessible from derived class objects?

Not quite. The base class members are hidden in the derived class, thus protecting them from unwanted interference.

Page 6: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

6

2. Types of Inheritance2. Types of Inheritance

2. Do the inherited non-private data members and methods of the base class retain their access type (public/protected) in the derived class? If not, how does the access change?

This depends on the type of inheritance defined for the derived class.

There are three types of inheritance: public, protected and private.

Broadly speaking: The inherited non-private members and methods of the base class

Retain their access type for public inheritance, i.e. public members remain public, protected members remain protected;

Are given protected access for protected inheritance, i.e. public members become protected, protected members remain protected;

Are given private access for private inheritance, i.e. public members become private, protected members become private;

In all types of inheritance the private members are hidden as pointed out in previous slide.

Page 7: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

7

Defining a Derived Class - SyntaxDefining a Derived Class - Syntax

Example:

class BCString : public { …. }String

In general:

class <DerivedClassName> : <InheritanceType> <BaseClassName> { …. }

inheritance list: may include more than one base class multiple inheritance

Note that the syntax of the derived class definition uses existing keywords (e.g. class, public) and symbols (e.g. colon) in a new arrangement, rather than introducing new ones.

Page 8: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

8

Case Study: derived class BCString adds bound check to user Case Study: derived class BCString adds bound check to user defined class Stringdefined class String

Given: user-defined class Given: user-defined class StringString that does that does notnot perform boundary checks perform boundary checks

The class is implemented in files

uString.h - containing the definition of String

uStringMem.cpp - containing the member function definitions of String

The class is identical to the String class discussed in the previous lecture, except for the lack of bound checks in the overloaded subscript operators. Thus the subscript prototypes take an int argument instead of unsigned

char& operator[] (int i); //Element of variable string at position i char operator[] (int i) const; //Element of constant string at position i

The int type is more natural and general (as it can be negative) type for an index argument as the previously used unsigned.

Page 9: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

9

class class String - Subscripts Member FunctionsString - Subscripts Member Functions

char& String::operator[](int i)//Element of variable string at position i {

return info_[i];}

char String::operator[](int i) const //Element of constant string at position i{

return info_[i];}

returns object

returns value

Page 10: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

10

3. Inheriting Base Class Members3. Inheriting Base Class Members

3. Does the derived class inherit all members (data and methods) of the base class? If yes, what happens when the base class methods do not make sense for the derived class objects?

Yes, all base class members are inherited. Even if the members of the base class do not make sense in the derived class. This will typically happen for some methods that are not specific enough for the derived class.

In the latter case the unsuitable functions and operators must be overridden.

In order to override a base method a method with the same name and signature must be declared in and defined for the derived class.

Example:Example: The BCString class overrides the subscript operators of the base String class

The BCString class is implemented in filesuStringDervd.h - containing the definition of BCString, anduStringDervdMem.cpp - containing the member function definitions of

BCString

Page 11: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

11

class class BCString - DefinitionBCString - Definition

class BCString : public String { public:

BCString(const char s[]="");//constructs deep copy of C-string s BCString(const BCString& s);//constructs deep copy of String type s ~BCString();//deallocates string memory

BCString& operator=(const BCString& rhs); //Assigns deep copy rhs BCString& operator+=(const BCString& rhs); //Appends deep copy of

rhs friend BCString operator+(const BCString& s, const BCString& t);

//Appends t to s

int length() const; //Returns number of string characters char& operator[](int i); //Element of variable string at position i char operator[](int i) const; //Element of constant string at position i

friend istream& operator>>(istream& in, BCString& bcs); /Reads <= 999 char to newline; Newline is extracted, but not assigned.

private: int length_; //length of string - new data member

};

Constructors and Destructor

public inheritance from class String hidden data member char* info_

Access Member Functions

Append and Assign

Input Functions

Page 12: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

12

4. Treating Derived Class Objects as Base Class Objects4. Treating Derived Class Objects as Base Class Objects

4. Can derived class objects be treated as base class objects?

Yes. Any derived class object is a base class object as it inherits all attributes of the base class, e.g. BCString has the hidden data member char* info_ from String

However, this does not mean that the base class methods will handle all members of the derived class appropriately.

Vice versa: Can base class objects be treated as derived class objects?

No. Base class objects are not derived class objects. e.g. String is clueless about the existence of the private data member int length_ in BCString

Page 13: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

13

Derived Class BCString Subscripts override Base Class String SubscriptDerived Class BCString Subscripts override Base Class String Subscript

char& BCString:: operator[](int i) {

if ( i>=0 && i<length_ ) return String :: operator[](i);

else{ cout<<"\nBoundary error - program exits"<<endl; exit(1);

}}

char BCString :: operator[](int i) const{

if(i>=0 && i<length_) return String:: operator[](i);

else{ cout<<"\nBoundary error - program exits"<<endl; exit(1);

}}

Base class operator for variable objects invoked if bounds are ok

Base class operator for constant objects invoked if bounds are ok

Same name and signature as base class function

Same name and signature as base class function

Page 14: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

14

5. Reusing Base Class Code to Define Derived Class 5. Reusing Base Class Code to Define Derived Class MethodsMethods

5. How can we reuse the code of base class methods while modifying them to suit/ take into account the new attributes of the derived class?

By using base case methods in the definitions of the derived class methods.

Example: Example:

a) Using the base class subscript in the definition of the derived class subscript as shown on the previous slide.

b) Using the base class constructors, destructor, and assignment operators to overload the derived class constructors, destructor, and assignment operators: the base class method are invoked to take care of the inherited base class data members; then appropriate statements are added for the new data members defined in the derived class.

Page 15: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

15

6. Constructors and Destructors are NOT Inherited6. Constructors and Destructors are NOT Inherited

6. Do we need new constructors and destructor for the derived class?

Yes, as we need to initialize/dispose of the data members defined in the derived class. Naturally the base class has no way of knowing anything about them.

Thus constructors and destructors are NOT inherited!!!

Note: this does not mean they do not exist. There is always a default constructor and destructor. But there is no guarantee whatsoever that the defaults will behave consistently with the definition of the derived class.

How do constructors/destructor of the derived class relate to the ones of the base class?

The base class constructors and destructors are used to take care of the inherited data members.

Page 16: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

16

Derived Class BCString - Constructors and DestructorDerived Class BCString - Constructors and Destructor

BCString :: BCString ( const char s[] ) : String(s), length_(strlen(s)) { }

BCString:: BCString(const BCString& bcs): String(bcs), length_(bcs.length_){}

BCString:: ~BCString() {}

automatically calls base class destructor ~String

Base class constructor with char array called

Base class constructor with BCString bcs called: works, because a BCString is also a base class String object (see question 4)

Page 17: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

17

7. Assignment Operators Are NOT Inherited 7. Assignment Operators Are NOT Inherited (Similarly to Constructors and Destructors)(Similarly to Constructors and Destructors)

7. Do we need new assignment operators for the derived class?

Yes, as we need to assign properly the data members defined in the derived class. Naturally the base class has no way of knowing anything about them.

Thus assignment operators are NOT inherited!!!

How do assignment operators of the derived class relate to the ones of the base class?

The base class assignment operators are called to take care of the inherited/hidden data members.

Page 18: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

18

Derived Class BCString -Overloaded Assign '=' OperatorDerived Class BCString -Overloaded Assign '=' Operator

BCString& BCString:: operator=(const BCString& rhs) //Needed for correct length_{

String:: operator=(rhs);

length_ = rhs.length_;

return *this;}

base class assignment handles base class data members

the data member added in the BCString is assigned appropriately

The append assign (+=) is handled similarly

Page 19: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

19

Derived Class BCString - Overloaded Append (+) uses its own Overloaded Derived Class BCString - Overloaded Append (+) uses its own Overloaded Append Assign (+=)Append Assign (+=)

BCString operator+(const BCString& s, const BCString& t)

{

BCString ret(s);

ret += t;

return ret;

}

BCString const reference arguments

overloaded assign append (+=) of BCString class used

BCString object for deep copy created

Page 20: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

20

Relationships: Inheritance and Composition

Inheritance provides an important mechanism for defining relationship between classes and building hierarchies of objects. The relationship between the derived and the base class is one of a general to a special case, and called the "is-a" relationship.

Another way for creating relationships between classes is to provide a class with a member that is also of class type.This method of building class relationship is called composition. The relationship between the two classes is one of the whole to its parts and called the "has-a" relationship.

is-aBase class Derived class

class Whole {…Part partMember;…

}

class Whole partMemberhas-a

Human headhas-a

Bird winghas-a

Page 21: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

21

Derived Class BCString - Printing BCString objects with the overloaded Derived Class BCString - Printing BCString objects with the overloaded insertion stream operator of the base class String insertion stream operator of the base class String

int main()

{

BCString a("Jane"), b("George");

cout<<"String a is "<< a <<" of length "<< a.length()<<endl;

cout<<"String b is "<< b <<" of length "<< b.length()<<endl;

String a is Jane of length 4

String b is George of length 6

Overloaded << String : works as BCString object is a String object as well (no << was overloaded for BCString as the idea is to print string info_, not the length_ added in BCString

Page 22: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

22

Derived Class BCString - BCString Subscripts and EqualityDerived Class BCString - BCString Subscripts and Equality

cout<< "\nThe positions of the letters in string a are:"<<endl;

for(int i=0; i< a.length(); i++) cout << "Position "<< i << " holds " << a[i] <<endl;

cout<< "\nThe positions of the letters in string b are:"<<endl; for( i=0; i< b.length(); i++)

cout << "Position "<< i << " holds " << b[i] <<endl;

if(a==b) cout<<"\nStrings a and b are equal"<<endl;

else cout<<"\nStrings a and b are not equal"<<endl;

The positions of the letters in string a are:Position 0 holds JPosition 1 holds aPosition 2 holds nPosition 3 holds e

The positions of the letters in string b are:Position 0 holds GPosition 1 holds ePosition 2 holds oPosition 3 holds rPosition 4 holds gPosition 5 holds e

[] of BCString overrides [] of the base String

== of base String (no == BCString needed)

Page 23: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

23

Derived Class BCString - Printing and Subscripts for const BCString Derived Class BCString - Printing and Subscripts for const BCString ObjectsObjects

const BCString message("Hello C++ experts!"); cout<<"The message is "<<message

<<"\nof length "<<message.length()<<endl; cout<< "\nThe positions of the letters in message are:"<<endl;

for( i=0; i< message.length(); i++)cout << "Position "<< i << " holds " << message[i] <<endl;

The message is Hello C++ experts!of length 18

The positions of the letters in message are:Position 0 holds HPosition 1 holds ePosition 2 holds lPosition 3 holds lPosition 4 holds oPosition 5 holdsPosition 6 holds CPosition 7 holds +Position 8 holds +Position 9 holds

[] const of BCString overrides [] const of the base String

Position 10 holds ePosition 11 holds xPosition 12 holds pPosition 13 holds ePosition 14 holds rPosition 15 holds tPosition 16 holds sPosition 17 holds !

Page 24: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

24

Derived Class BCString - Arrays of BCString ObjectsDerived Class BCString - Arrays of BCString Objects

BCString friendList[5]; cout<<"\nBegin input for list of five friends:"<<endl; for(i=0; i<5 ; i++){

cout<<"Enter name "<< i+1 <<":"; cin>>friendList[i];

}

Begin input for list of five friends:Enter name 1:Jane PaulEnter name 2:Annette GoldenEnter name 3:David BraunEnter name 4:Sam CrownEnter name 5:Nathaniel Hastings

overloaded >> BCString( info_initialized through String constructor; length_ initialized through BCString constructor)

Page 25: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

25

Derived Class BCString - Arrays of BCString ObjectsDerived Class BCString - Arrays of BCString Objects

cout<<"\n Your list of five friends contains:"<<endl; for(i=0; i<5 ; i++)

cout<<" >"<< friendList[i] <<" and the length is " <<friendList[i].length()<<endl;

cout<< "Value of 2th element of first friend is "<< friendList[0][1]<<endl; cout<< "Value of 20th element of first friend is "<< friendList[0][19]<<endl;

Your list of five friends contains: >Jane Paul and the length is 9 >Annette Golden and the length is 14 >David Braun and the length is 11 >Sam Crown and the length is 9 >Nathaniel Hastings and the length is 18Value of 2th element of first friend is a

Boundary error - program exits

access method length() invoked with BCString instance friendList[i]

overloaded [] for position 1with BCString instance friendList[0]

overloaded [] for illegal position 19with BCString instance friendList[0]

Page 26: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

26

Inheritance - Summary• Inheritance is the basic mechanism of the OO design and programming for adding functionality to a program by reusing the existing code in a systematic and consistent way.

• The main idea of inheritance is to build class hierarchies where the most general properties are implemented in a base class and specialization is added in the derived classes.

• Derived classes inherit all members of their base class.

• The access type of the inherited members in the derived class is determined by the inheritance type that can be

public: public and protected members retain their access type; protected: public and protected members are protected; private: public and protected members become private;

Inherited private class members are always hidden in the derived class and derived class objects have no access to them in order to preserve the encapsulation principle

Page 27: 11/24/08MET CS 563 - Fall 2008 9. Inheritance 1 10. Inheritance - Reusing and Augmenting Code Overriding Theme of OO Design and Programming: reuse existing

11/24/08 MET CS 563 - Fall 2008 9. Inheritance

27

Inheritance - Summary (continued)

• Derived class objects can be treated as base class objects but not vice versa.

• Inherited base class methods that do not make sense for the derived class can be overridden by defining a method with the same name and signature for the derived class.

• Derived class methods can and should be extended by using the corresponding base class method and only adding the code for the members newly introduced in the derived class.

• Constructors, destructors and assignment operators are not inherited as the base class has no way of knowing what will be added in the derived class.

•In addition to inheritance that implements an "is-a" relationship and corresponding hierarchy, one can implement class relationships through a "has-a" relationship and corresponding hierarchy. In the "has-a" relationship a class has a member of class type. The "is-a" relationship is a relation of the specific to the general. In contrast, to the the "has-a" relationship is a relationship of the whole to its parts.