Computer Science Department Inheritance. Computer Science Department Contents Composition (or...

73
Computer Science Department Inheritance

Transcript of Computer Science Department Inheritance. Computer Science Department Contents Composition (or...

Page 1: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Inheritance

Page 2: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Contents• Composition (or containership)

– Objects as Members of Classes• Concept of Inheritance• Levels of access control

CPS235:Inheritance 2

Page 3: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Composition vs Inheritance • Composition – A “has a” relationship

– An employee has a name, id, salary – Class member data can contain basic data

types as well as objects of other classes– An employee has a date of birth and date of

hiring and these can be represented by objects of a date class

• Inheritance – A “kind of” or “is a” relationship– An employee can be a laborer, a scientist, a

manager, an engineer– These are all examples of a more general

category of employees– So a laborer is an employee, so is a scientist

and so on…CPS235:Inheritance 3

Page 4: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Composition/ContainershipObjects as members of a class

CPS235:Inheritance 4

Page 5: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

2003 Prentice Hall, Inc.All rights reserved.

Outline5

date1.h (1 of 1)

#include <iostream>

#include<conio>

7 class Date {8 9 public:10 Date( int = 1, int = 1, int = 1900 ); // default constructor

11 void print() const; // print date in month/day/year format

12 ~Date(); // provided to confirm destruction order

13 Date (const Date& d); //copy constructor13 14 private:15 int month; // 1-12 (January-December)16 int day; // 1-31 based on month17 int year; // any year18 22 }; // end class Date

Page 6: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

2003 Prentice Hall, Inc.All rights reserved.

Outline6

date1.cpp (1 of 3)

11 Date::Date( int mn, int dy, int yr )14 {15 if ( mn > 0 && mn <= 12 ) // validate the month16 month = mn;17 18 else { // invalid month set to 119 month = 1;20 cout << "Month " << mn << " invalid. Set to month 1.\n";21 }22 23 year = yr; // should validate yr• day = dy; // output Date object to show when its constructor is called27 cout << "Date object constructor for date "; 28 print(); 29 cout << endl; 30 • } // end Date constructor void Date::print() const35 {36 cout << month << '/' << day << '/' << year; 37 38 } // end function print39 40 // output Date object to show when its destructor is called41 Date::~Date() 42 { 43 cout << "Date object destructor for date "; 44 print(); • cout << endl; • getch(); 46 47 } // end destructor ~Date

Page 7: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

2003 Prentice Hall, Inc.All rights reserved.

Outline7

date1.cpp (2 of 3)

//Copy constructor

Date::Date(const Date& d)

{

month = d.month;

day = d.day;

year = d.year;

cout<<“copy constructor for date object";

print();

cout<<endl;

}

Page 8: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

2003 Prentice Hall, Inc.All rights reserved.

Outline8

employee1.h (1 of 2)

class Employee {11 public:13 Employee(

14 const char [], const char [], const Date &, const Date & );

15 void print() const;17 ~Employee(); // provided to confirm destruction order

18 19 private:20 char firstName[ 25 ];21 char lastName[ 25 ];22 const Date birthDate; // composition: member object23 const Date hireDate; // composition: member object24 25 }; // end class Employee

Page 9: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

2003 Prentice Hall, Inc.All rights reserved.

Outline

employee1.cpp(2 of 3)

13 // constructor uses member initializer list to pass initializer14 // values to constructors of member objects birthDate and 15// hireDate [Note: This invokes the "default copy constructor“]

17 Employee::Employee( const char first[], const char last[], 18 const Date &dateOfBirth, const Date &dateOfHire ) 19 : birthDate( dateOfBirth ), // initialize birthDate 20 hireDate( dateOfHire ) // initialize hireDate 21 {22 // copy first into firstName and be sure that it fits23 int length = strlen( first );24 length = ( length < 25 ? length : 24 );25 strncpy( firstName, first, length );26 firstName[ length ] = '\0';27 28 // copy last into lastName and be sure that it fits29 length = strlen( last );30 length = ( length < 25 ? length : 24 );31 strncpy( lastName, last, length );32 lastName[ length ] = '\0';33 34 // output Employee object to show when constructor is called35 cout << "Employee object constructor: " 36 << firstName << ' ' << lastName << endl; }

Member initializer syntax to initialize Date data members birthDate and hireDate; compiler uses the copy constructor of Date class

Output to show timing of constructors.

Page 10: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

2003 Prentice Hall, Inc.All rights reserved.

Outline10

employee1.cpp(3 of 3)

40 // print Employee object41 void Employee::print() const42 {43 cout << lastName << ", " << firstName << "\nHired: ";44 hireDate.print();45 cout << " Birth date: ";46 birthDate.print();47 cout << endl;48 49 } // end function print50 51 // output Employee object to show when its destructor is called52 Employee::~Employee() 53 { 54 cout << "Employee object destructor: " • << lastName << ", " << firstName << endl;• getch(); 56 57 } // end destructor ~Employee

Output to show timing of destructors.

Page 11: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

2003 Prentice Hall, Inc.All rights reserved.

Outline11

fig07_10.cpp(1 of 1)

3 #include <iostream>4 10 int main()11 {12 Date birth( 7, 24, 1949 ); 13 Date hire( 3, 12, 1988 ); 14 Employee manager( "Bob", "Jones", birth, hire );

getch();15 16 cout << '\n';3 manager.print();4 cout<<‘\n’;5 6 Employee clone(“Rob”, “Jones”, birth, hire);7 cout<<‘\n’;8 clone.print();9 getch();

23 return 0;24 25 } // end main

Create Date objects to pass to Employee constructor.

Page 12: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Output

CPS235:Inheritance 12

Note two additional Date objects constructed; copy constructor used

Destructor for host object manager runs before destructors for member objects hireDate and birthDate.

Destructor for Employee’s member object hireDate.

Destructor for Employee‘s member object birthDate.Destructor for Date

object hire.Destructor for Date object birth.

Page 13: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Inheritance• Inheritance is a relationship between two

or more classes where derived class inherits behaviour and attributes of pre-existing (base) classes

• Intended to help reuse of existing code with little or no modification

CPS235:Inheritance 13

Page 14: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Inheritance• Inheritance can be continuous

– Derived class can inherit from a base class– The derived class can act as a base class and

another class can inherit from it – If you change the base class, all derived classes

also change– Any changes in the derived class do not change

the base class– All features of the base class are available in

the derived class• However, the additional features in the

derived class are not available in the base class

CPS235:Inheritance 14

Page 15: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 15

Page 16: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance16

Inheritanceab

Class A

Features: a,b

c

Class B

Features: a,b,c

de

Class C

Features: a,b,d,e

f

Class D

Features: a,b,d,e,f

Page 17: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Inheritance and Encapsulation• private member

– Is accessible only via the base class

• public member– Is accessible everywhere (base class, derived

class, othe classes)

• protected member– Is accessible by the base class and derived

classes

Page 18: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 18

Inheritance Concept

Rectangle Triangle

Polygon

class Polygon{private:

int width, length;public:

void set(int w, int l);

};

class Rectangle{private: int width, length;public: void set(int w, int

l); int area();};

class Triangle{private: int width, length;public: void set(int w, int

l); int area();};

Page 19: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 19

Rectangle Triangle

Polygonclass Polygon

{

protected:

int width, length;

public:

void set(int w, int l);

};

class Rectangle: public Polygon

{public: int area();

};

class Rectangle{

protected:

int width, length;

public:

void set(int w, int l);

int area();

};

Inheritance Concept

Page 20: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 20

Rectangle Triangle

Polygonclass Polygon

{

protected:

int width, length;

public:

void set(int w, int l);

};

class Triangle : public Polygon

{public:

int area();};

class Triangle{

protected:

int width, length;

public:

void set(int w, int l);

int area();

};

Inheritance Concept

Page 21: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 21

Inheritance Concept

Point

Circle 3D-Point

class Point{

protected: int x, y;public: void set(int a, int b);

};

class Circle : public Point{

private: double r;

};

class 3D-Point: public Point{

private: int z;

};

xy

xyr

xyz

Page 22: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Declaring Inheritance• Syntax:

class DerivedClassName : access-level BaseClassName

where – access-level specifies the type of derivation

•private by default, or•public or•protected (used very rarely)

CPS235:Inheritance 22

Page 23: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 23

Class DerivationPoint

3D-Point

class Point{protected: int x, y;public: void set(int a, int b);

};

class 3D-Point : public Point{private: double z;… …

};

class Sphere : public 3D-Point{private: double r;… …

};

Sphere

Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere

Page 24: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

What to Inherit?• In principle, every member of a base class

is inherited by a derived class

– just with different access permission

CPS235:Inheritance 24

Page 25: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 25

Access Control Over the Members

• Two levels of access control over class members– class definition– inheritance type

base c lass / supe rc lass /pa ren t c lass

deriv ed c lass / subc lass /ch ild c lass

deriv

e fro

m

mem

bers

goe

s to

class Point{protected: int x, y;public: void set(int a, int b);

};

class Circle : public Point{… …

};

Page 26: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Member Access Control

• There are 3 levels of member (data or methods) access control:– public: members can be used by itself and the whole

world; any function can access them– protected: methods (and friends) of itself and any

derived class can use it– private: members can only be used by its own methods

(and its friends)• We’ll study friend functions later

• Without inheritance, private and protected have the same meaning

• The only difference is that methods of a derived class can access protected members of a base class, but cannot access private members of a base class

CPS235:Inheritance 26

Page 27: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Access Rights of Derived Classes

• The type of inheritance defines the minimum access level for the members of derived class that are inherited from the base class

• With public inheritance, the derived class follows the same access permission as in the base class

• With protected inheritance, only the public members inherited from the base class can be accessed in the derived class as protected members

• With private inheritance, none of the members of base class is accessible by the derived class

private protected

public

private private private private

protected

private protected protected

public private protected public

Type of Inheritance

Access

Con

trol

for M

em

bers

Page 28: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Access Rights of Derived Classes• Take these classes as examples:

  class B                    { /*...*/ }; class D_priv : private   B { /*...*/ }; class D_prot : protected B { /*...*/ }; class D_publ : public    B { /*...*/ }; class UserClass          { B b; /*...*/ };

• None of the derived classes can access anything that is private in B

• In D_priv, the public and protected parts of B are private

• In D_prot, the public and protected parts of B are protected

• In D_publ, the public parts of B are public and the protected parts of B are protected (D_publ is-a-kind-of-a B)

• class UserClass can access only the public parts of B, which "seals off" UserClass from B

CPS235:Inheritance 28

Page 29: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 29

protected vs. privateSo why not always use protected instead of private?

– Because protected means that we have less encapsulation– All derived classes can access protected data

members of the base class– Assume that later you decided to change the

implementation of the base class having the protected data members– For example, we might want to represent address

by a new class called Address instead of string– If the address data member is private, we can

easily make this change – The class documentation does not need to be

changed.– If it is protected, we have to go through all derived

classes and change them– We also need to update the class documentation.

Page 30: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 30

Class Derivation Example

mother

daughter son

class mother{protected: int x, y;public: void set(int a, int b);private: int z;

};

class daughter : public mother{private:

double a;public:

void foo ( );};

void daughter :: foo ( ){x = y = 20;set(5, 10); cout<<“value of a ”<<a<<endl; z = 100; // error, a private member

};

daughter can access 3 of the 4 inherited members

Page 31: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 31

Class Derivation Examplemother

daughter son

class mother{protected: int x, y;public: void set(int a, int b);private: int z;

}

class son : private mother{private:

double b;public:

void foo ( );}

void son :: foo ( ){x = y = 20; set(5, 10); cout<<“value of b ”<<b<<endl; z = 100; // error, not a public member

}

son can also access 3 of the 4 inherited members

Page 32: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 32

mother

daughter son

granddaughter grandson

Class Derivation Example

class mother{protected: int x, y;public: void set(int a, int b);private: int z;

};

class daughter : public mother{private:

double a;public:

void foo ( );};

class granddaughter : public daughter{public:

void foo ( );};

Page 33: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 33

void granddaughter :: foo ( ){x = y = 20; //OKset(5, 10); //OKcout<<“value of a ”<<a<<endl; //error: private member of daughterz = 100; // error, a private member of mother

};

Class Derivation Example

Page 34: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 34

mother

daughter son

granddaughter grandson

class mother{protected: int x, y;public: void set(int a, int b);private: int z;

};

class son : private mother{private:

double b;public:

void foo ( );};

class grandson : public son{public:

void foo ( );};

Class Derivation Example

Page 35: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 35

void grandson:: foo ( ){x = y = 20; //ERROR: not accessibleset(5, 10); //ERROR: not accessible

z = 100; // error, a private member of mother

};

Class Derivation Example

Page 36: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Encapsulationclass Figure { protected: int x, y;};

class Circle : public Figure { public: int radius;};

int main() { Circle a; a.x = 0; a.y = 0; a.radius = 10;}

Page 37: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Encapsulationclass Figure { protected: int x_, y_;};

class Circle : public Figure

{ private: int radius_; public: Circle(int x, int

y, int radius);};

Circle::Circle(int x, int y, int radius)

{ x_ = x; y_ = y; radius_ = radius;}

int main() { Circle a(0,0,10);}

Page 38: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Encapsulationclass Figure { private: int x_, y_;};

class Circle : public Figure

{ private: int radius_; public: Circle(int x, int

y, int radius);};

Circle::Circle(int x, int y, int radius)

{ x_ = x; y_ = y; radius_ = radius;}

int main() { Circle a(0,0,10);}

Page 39: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Encapsulationclass Figure { private: int x_, y_; public: void SetX(int x); void SetY(int y);};void Figure::SetX(int x)

{ x_ = x;}void Figure::SetY(int y)

{ y_ = y;}

class Circle : public Figure

{ private: int radius_; public: Circle(int x, int y, int radius);

};Circle::Circle(int x, int y, int radius)

{ SetX(x); SetY(y); radius_ = radius;}int main() { Circle a(0,0,10);}

Page 40: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

What to Inherit?• In principle, every member of a base class

is inherited by a derived class– just with different access permission

• However, there are exceptions for– Constructor and destructor – Overloaded Assignment operator– Friends

Since all these functions are class-specific!

CPS235:Inheritance 40

Page 41: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Constructor Rules for Derived Classes • The default constructor and the destructor of the

base class are always called when a new object of a derived class is created or destroyed

CPS235:Inheritance 41

class A { public:

A ( )

{cout<<“A:default”<<endl;}

A (int a)

{cout<<“A:parameter”<<endl;}

};

class B : public A { public:

B (int a) {cout<<“B”<<endl;}

};

B test(1);A:defaultB

output:

Page 42: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Constructor Rules for Derived Classes • You can also specify a constructor of the base class other

than the default constructorDerivedClassCon ( derivedClass args ) : BaseClassCon

( baseClass args )

{ DerivedClass constructor body }

CPS235:Inheritance 42

class A { public:

A ( )

{cout<<“A:default”<<endl;}

A (int a)

{cout<<“A:parameter”<<endl;}

};

class B : public A { public:

B (int a):A(a) {cout<<“B”<<endl;}

};

B test(1);A:parameterB

output:

Page 43: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 43

What is the result?

class Figure { public: Figure() { cout << "Figure

Constructor\n"; } ~Figure() { cout << "Figure

Destructor\n"; }};

class Circle : public Figure

{ public: Circle() { cout << "Circle

Constructor\n"; } ~Circle() { cout << "Circle

Destructor\n"; }};

int main() { Circle a;}

Page 44: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Constructor Rules for Derived Classes • Base constructor is called before the

derived class constructor• Destructors vice versa

CPS235:Inheritance 44

Page 45: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Calling the Base Class constructorclass Figure { public: Figure() { cout << "Figure

Constructor\n"; } ~Figure() { cout << "Figure

Destructor\n"; }};

class Circle : public Figure

{ public: Circle() : Figure() { cout << "Circle

Constructor\n"; } ~Circle() { cout << "Circle

Destructor\n"; }};

int main() { Circle a;}

Page 46: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Calling the Base Class constructorclass Figure { private: int x, y; public: Figure(int xVal, int

yVal):x(xVal), y(yVal) { cout << "Figure

Constructor\n"; } ~Figure() { cout << "Figure

Destructor\n"; }};

class Circle : public Figure

{ private: double radius; public: Circle(int xVal, int

yVal, int r) : Figure(xVal, yVal), radius(r)

{ cout << "Circle

Constructor\n"; } ~Circle() { cout << "Circle

Destructor\n"; }};

int main() { Circle a(0,0,5);}

Page 47: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 47

Define its Own Members

Point

Circle

class Point{protected: int x, y;public: void set(int a, int b);

};

class Circle : public Point{private:

double r;public:

void set_r(double c);

};

xy

xyr protected:

int x, y;private: double r;public: void set(int a, int b); void set_r(double c);

The derived class can also define its own members, in addition to the members inherited from the base class

Page 48: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 48

Even more …• A derived class can override methods defined

in its parent class. With overriding, – the method in the subclass has the identical

signature to the method in the base class– a subclass implements its own version of a base

class methodclass A { protected:

int x, y; public:

void print (){cout<<“From A”<<endl;}

};

class B : public A { public:

void print ()

{cout<<“FromB”<<endl;}

};

Page 49: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 49

class Point{

protected: int x, y;public: void set(int a, int b)

{x=a; y=b;} void foo (); void print();

};

class Circle : public Point{ private: double r; public:

void set (int a, int b, double c) { Point :: set(a, b); //same name function call r = c;}void print(); };

Access a Method

Circle C;C.set(10,10,100); // from class CircleC.foo (); // from base class PointC.print(); // from class Circle

Point A;A.set(30,50); // from

base class PointA.print(); // from

base class Point

Page 50: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 50

Putting It All Together• Time is the base class• ExtTime is the derived

class with public inheritance

• The derived class can– inherit all members from the

base class, except the constructor

– access all public and protected members of the base class

– define its private data member

– provide its own constructor– define its public member

functions– override functions inherited

from the base class

ExtTime

Time

Page 51: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 51

Time class example

Page 52: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 52

class Timeclass Time{ public: Time () :hrs(0),mins(0),secs(0){}

Time (int h, int m, int s):hrs(h),mins(m),secs(s){} void Set ( int h, int m, int s )

{hrs =h;mins=m;secs=s;}void Increment ( )

{cout<<"Calling base class Increment"<<endl;}void Write ( ) const {cout<<hrs<<":"<<mins<<":"<<secs;}

protected : int hrs ;

int mins ;int secs ;

} ;

Page 53: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 53

Class Interface Diagram

Protected data:

hrs

mins

secs

Set

Increment

Write

Time

Time

Time class

Page 54: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Derived Class ExtTime enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT,

PDT } ;class ExtTime : public Time // Time is the base

class and use public inheritance{ public : void Set ( int h, int m, int s, ZoneType

timeZone ) ; void Write ( ) const; //overridden ExtTime(int h, int m, int s,ZoneType z) ; ExtTime(); // default constructor

private :ZoneType zone ; // added data member

} ;

CPS235:Inheritance 54

Page 55: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 55

Class Interface Diagram

Protected data:

hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data: zone

Page 56: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 56

Implementation of ExtTime

Default Constructor

ExtTime :: ExtTime (){ zone = EST ;

}

The default constructor of base class, Time(), is automatically called, when an ExtTime object is created

ExtTime et1;

hrs = 0mins = 0secs = 0zone =

EST

et1

Page 57: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

CPS235:Inheritance 57

Implementation of ExtTimeAnother Constructor

ExtTime :: ExtTime (int h, int m, int s, ZoneType z): Time (h, m, s),zone(z) {}

ExtTime et2 (8,30,0,EST);

hrs = 8mins = 30secs = 0zone = EST

et2

Page 58: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Derived Class ExtTime ExtTime :: ExtTime ():zone(EST){}

ExtTime :: ExtTime (int h, int m, int s, ZoneType z) : Time (h, m, s),zone(z) {}

void ExtTime :: Set(int h,int m,int s, ZoneType z){ Time :: Set (h, m, s); // calling same name

function of the base class

zone = z;}

void ExtTime ::Write()const // function overriding{ string zoneString[8] =

{"EST", "CST", "MST", "PST", "EDT", "CDT", "MDT", "PDT"} ;

Time :: Write ( ) ; // calling same name function of the base class

cout <<' '<<zoneString[zone]<<endl;}

CPS235:Inheritance 58

Page 59: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Using class ExtTimeint main(){

ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ;

thatTime.Write( ); // prints 00:00:00 EST

thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // prints 16:49:23 CDT

thisTime.Increment ( ) ; //prints Calling Base Class Increment

thisTime.Increment ( ) ; //prints Calling Base Class Increment

thisTime.Write ( ) ; // prints 08:35:02 PST getch();}

CPS235:Inheritance 59

Page 60: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Multiple Inheritance#include <iostream>class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b;} };class COutput { public: void output (int i); };

void COutput::output (int i) { cout << i << endl; }

CPS235:Inheritance 60

Page 61: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Multiple Inheritanceclass CRectangle: public CPolygon, public COutput { public: int area () { return (width * height); } };

class CTriangle: public CPolygon, public COutput { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); rect.output (rect.area()); trgl.output (trgl.area()); return 0;}

CPS235:Inheritance 61

Page 62: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Ambiguities in Multiple Inheritance• See code examples

CPS235:Inheritance 62

Page 63: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Friend functions• A friend function of a class is defined outside that

class's scope, yet has the right to access the non-public (and public) members of the class

• Let’s say you want a function to operate on objects of two different classes and access their private data, you would need to use a friend function

CPS235:Inheritance 63

Page 64: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Example of friend functionsclass beta; //req for frifunc declaration class alpha{

private: int data; public: alpha():data(3) {} friend int frifunc(alpha, beta); //friend

func declaration

};

class beta{

private: int data; public: beta():data(7) {} friend int frifunc(alpha,beta); //friend

func declaration

};CPS235:Inheritance 64

A class cannot be referred to until it has been declared

Page 65: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Example of friend functionsint frifunc(alpha a, beta b) //friend func

defined{

return (a.data + b.data);}

void main(){

alpha aa; beta bb; cout<<frifunc(aa,bb)<<endl; //friend func

called getch();}

CPS235:Inheritance 65

Page 66: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

friend classes• The member functions of a class can all be made

friends at the same time when you make the entire class a friend

• If class alpha declares class beta as a friend class, then all member functions of class beta can access private data of class alpha

• It is also possible to declare only one member function of another class to be a friend

CPS235:Inheritance 66

Page 67: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

friend classesclass beta;class alpha{

private: int data; public: alpha():data(3) {} friend class beta; //friend class

declaration};

class beta{

public: void func(alpha a) { cout<<"alpha's data: "<<a.data; }};

CPS235:Inheritance 67

Page 68: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

friend classesvoid main(){

alpha aa; beta bb; bb.func(aa); getch();}

CPS235:Inheritance 68

Page 69: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Class member functions as friends class CSquare;class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a);};

class CSquare { private: int side; public: void set_side (int a) {side=a;} friend void CRectangle::convert(CSquare);};

CPS235:Inheritance 69

Page 70: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Class member functions as friends void CRectangle::convert (CSquare a) { width = a.side; height = a.side;}

int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); getch(); return 0;}

CPS235:Inheritance 70

Page 71: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Summary (friends)• Even though the prototypes for friend functions

appear in the class definition, friends are not member functions

• Friend declarations can be placed anywhere in a class definition either in public, private or protected sections

• Violates the data hiding principle of classes, so it should be avoided as much as possible

• Friendship is granted, not taken i.e., for class B to be a friend of class A, class A must explicitly declare that class B is its friend

• The friendship relation is neither symmetric nor transitive

CPS235:Inheritance 71

Page 72: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Exercise• Consider a publishing company that markets both book and

audio-cassette versions of its work• Create a class “publication” that stores the title (a string) and

price (type float) of a publication• Create a class sales that holds an array of three floats so that

it can record the sales of a particular publication for the last three months

• Derive two classes: “book”, which adds a page count (type int); and “tape”, which adds a playing time in minutes(type float) from both publication and sales. Each of these four classes should have a getdata() function to get its data from the user and putdata() function to display its data

• An object of class book or tape should input and output publication as well as sales data along with its own data

• Write a main() function to create a book object and a tape object and exercise their input/output capabilities

CPS235:Inheritance 72

Page 73: Computer Science Department Inheritance. Computer Science Department Contents Composition (or containership) –Objects as Members of Classes Concept of.

Computer Science Department

Compulsory Reading• Deitel and Deitel (5th edition)

– Topic: 10.3. Composition: Objects as Members of Classes

– Topic: 10.4. Friend functions and Friend classes

• Robert Lafore– Chapter 9: Inheritance (complete)– Chapter 11: Topic: Friend functions (starts on

page 572 in the e-book)

CPS235:Inheritance 73