chapter 12 - object-oriented programming: inheritance

43
1 Chapter 12 - Object- Oriented Programming: Inheritance Outline 12.1 Introduction 12.2 Base Classes and Derived Classes 12.3 protected Members 12.4 Relationship between Base Classes and Derived Classes 12.5 Case Study: Three-Level Inheritance Hierarchy 12.6 Constructors and Destructors in Derived Classes 12.7 “Uses A” and “Knows A” Relationships 12.8 public, protected and private Inheritance 12.9 Software Engineering with Inheritance

Upload: hovan

Post on 05-Jan-2016

52 views

Category:

Documents


0 download

DESCRIPTION

Chapter 12 - Object-Oriented Programming: Inheritance. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 12 - Object-Oriented Programming: Inheritance

1

Chapter 12 - Object-Oriented Programming: Inheritance

Outline12.1 Introduction12.2 Base Classes and Derived Classes12.3 protected Members12.4 Relationship between Base Classes and Derived Classes12.5 Case Study: Three-Level Inheritance Hierarchy12.6 Constructors and Destructors in Derived Classes12.7 “Uses A” and “Knows A” Relationships12.8 public, protected and private Inheritance12.9 Software Engineering with Inheritance

Page 2: Chapter 12 - Object-Oriented Programming: Inheritance

2

12.1 Introduction• Inheritance

– Software reusability– Create new class from existing class

• Absorb existing class’s data and behaviors• Enhance with new capabilities

– Derived class inherits from base class• Derived class

– More specialized group of objects

– Behaviors inherited from base class

» Can customize

– Additional behaviors

Page 3: Chapter 12 - Object-Oriented Programming: Inheritance

3

12.1 Introduction• Class hierarchy

– Direct base class• Inherited explicitly (one level up hierarchy)

– Indirect base class• Inherited two or more levels up hierarchy

– Single inheritance• Inherits from one base class

– Multiple inheritance• Inherits from multiple base classes

– Base classes possibly unrelated

Page 4: Chapter 12 - Object-Oriented Programming: Inheritance

4

12.1 Introduction• Three types of inheritance

– public • Every object of derived class also object of base class

– Base-class objects not objects of derived classes– Example: All cars vehicles, but not all vehicles cars

• Can access non-private members of base class– Derived class can effect change to private base-class members

» Through inherited non-private member functions

– private• Alternative to composition

– protected • Rarely used

Page 5: Chapter 12 - Object-Oriented Programming: Inheritance

5

12.1 Introduction• Abstraction

– Focus on commonalities among objects in system

• “is-a” vs. “has-a”– “is-a”

• Inheritance

• Derived class object treated as base class object

• Example: Car is a vehicle– Vehicle properties/behaviors also car properties/behaviors

– “has-a”• Composition

• Object contains one or more objects of other classes as members

• Example: Car has a steering wheel

Page 6: Chapter 12 - Object-Oriented Programming: Inheritance

6

12.2 Base Classes and Derived Classes

• Base classes and derived classes– Object of one class “is an” object of another class

• Example: Rectangle is quadrilateral.– Class Rectangle inherits from class Quadrilateral– Quadrilateral: base class– Rectangle: derived class

– Base class typically represents larger set of objects than derived classes

• Example: – Base class: Vehicle

» Cars, trucks, boats, bicycles, …

– Derived class: Car» Smaller, more-specific subset of vehicles

Page 7: Chapter 12 - Object-Oriented Programming: Inheritance

7

12.2 Base Classes and Derived Classes

• Inheritance examplesBase class Derived classes

Student GraduateStudent UndergraduateStudent

Shape Circle Triangle Rectangle

Loan CarLoan HomeImprovementLoan MortgageLoan

Employee FacultyMember StaffMember

Account CheckingAccount SavingsAccount

Page 8: Chapter 12 - Object-Oriented Programming: Inheritance

8

12.2 Base Classes and Derived Classes

• Inheritance hierarchy– Inheritance relationships: tree-like hierarchy structure

– Each class becomes• Base class

– Supply data/behaviors to other classes

OR

• Derived class– Inherit data/behaviors from other classes

Page 9: Chapter 12 - Object-Oriented Programming: Inheritance

9

Single inheritance

CommunityMember

Employee Student

Administrator Teacher

AdministratorTeacher

StaffFaculty

Alumnus

Single inheritance

Single inheritance

Multiple inheritance

Fig. 12.2 Inheritance hierarchy for university CommunityMembers.

Page 10: Chapter 12 - Object-Oriented Programming: Inheritance

10

Shape

TwoDimensionalShape ThreeDimensionalShape

Circle Square Triangle Sphere Cube Tetrahedron

Fig. 12.3 Inheritance hierarchy for Shapes.

Page 11: Chapter 12 - Object-Oriented Programming: Inheritance

11

12.2 Base Classes and Derived Classes

• public inheritance– Specify with:

Class TwoDimensionalShape : public Shape• Class TwoDimensionalShape inherits from class Shape

– Base class private members• Not accessible directly

• Still inherited– Manipulate through inherited member functions

– Base class public and protected members• Inherited with original member access

– friend functions• Not inherited

Page 12: Chapter 12 - Object-Oriented Programming: Inheritance

12

protected Members

• protected access– Intermediate level of protection between public and private

– protected members accessible to• Base class members

• Base class friends

• Derived class members

• Derived class friends

– Derived-class members• Refer to public and protected members of base class

– Simply use member names

Page 13: Chapter 12 - Object-Oriented Programming: Inheritance

13

Relationship between Base Classes and Derived Classes

• Base class and derived class relationship– Example: Point/circle inheritance hierarchy

• Point– x-y coordinate pair

• Circle– x-y coordinate pair

– Radius

Page 14: Chapter 12 - Object-Oriented Programming: Inheritance

14

class Rectangle{

private:

int numVertices;

float xCoord, yCoord;

public:

void set(float x, float y, int nV);

float area();

};

Inheritance Concept

Rectangle Triangle

Polygon

class Polygon{

private:

int numVertices;

float xCoord, yCoord;

public:

void set(float x, float y, int nV);

};

class Triangle{

private:

int numVertices;

float xCoord, yCoord;

public:

void set(float x, float y, int nV);

float area();

};

Page 15: Chapter 12 - Object-Oriented Programming: Inheritance

15

Rectangle Triangle

Polygonclass Polygon{

protected:

int numVertices;

float xCoord, float yCoord;

public:

void set(float x, float y, int nV);

};

class Rectangle : public Polygon{

public:

float area();

};

class Rectangle{

protected:

int numVertices;

float xCoord, float yCoord;

public:

void set(float x, float y, int nV);

float area();

};

Inheritance Concept

Page 16: Chapter 12 - Object-Oriented Programming: Inheritance

16

Rectangle Triangle

Polygonclass Polygon{

protected:

int numVertices;

float xCoord, float yCoord;

public:

void set(float x, float y, int nV);

};

class Triangle : public Polygon{

public:

float area();

};

class Triangle{

protected:

int numVertices;

float xCoord, float yCoord;

public:

void set(float x, float y, int nV);

float area();

};

Inheritance Concept

Page 17: Chapter 12 - Object-Oriented Programming: Inheritance

17

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 18: Chapter 12 - Object-Oriented Programming: Inheritance

18

• Augmenting the original class

• Specializing the original class

Inheritance Concept

RealNumber

ComplexNumber

ImaginaryNumber

Rectangle Triangle

Polygon Point

Circle

realimag

real imag

3D-Point

Page 19: Chapter 12 - Object-Oriented Programming: Inheritance

19

Why Inheritance ?

Inheritance is a mechanism for

• building class types from existing class types

• defining new class types to be a – specialization – augmentation

of existing types

Page 20: Chapter 12 - Object-Oriented Programming: Inheritance

20

Define a Class Hierarchy

• Syntax:

class DerivedClassName : access-level BaseClassName

where

– access-level specifies the type of derivation

• private by default, or

• public

• Any class can serve as a base class– Thus a derived class can also be a base class

Page 21: Chapter 12 - Object-Oriented Programming: Inheritance

21

Class Derivation

Point

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 22: Chapter 12 - Object-Oriented Programming: Inheritance

22

What to inherit?

• In principle, every member of a base class is inherited by a derived class– just with different access permission

Page 23: Chapter 12 - Object-Oriented Programming: Inheritance

23

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 24: Chapter 12 - Object-Oriented Programming: Inheritance

24

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 – operator=() member – friends

Since all these functions are class-specific

Page 25: Chapter 12 - Object-Oriented Programming: Inheritance

25

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.

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 26: Chapter 12 - Object-Oriented Programming: Inheritance

26

Constructor Rules for Derived Classes You can also specify an constructor of the base class other than the default constructor

class A {

public:

A ( )

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

A (int a)

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

};

class C : public A {

public:

C (int a) : A(a)

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

};

C test(1);A:parameterC

output:

DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args )

{ DerivedClass constructor body }

Page 27: Chapter 12 - Object-Oriented Programming: Inheritance

27

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

class Circle{

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 28: Chapter 12 - Object-Oriented Programming: Inheritance

28

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 method.

class A {

protected:

int x, y;

public:

void print ()

{cout<<“From A”<<endl;}

};

class B : public A {

public:

void print ()

{cout<<“From B”<<endl;}

};

Page 29: Chapter 12 - Object-Oriented Programming: Inheritance

29

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 Circle

C.foo (); // from base class Point

C.print(); // from class Circle

Point A;

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

A.print(); // from base class Point

Page 30: Chapter 12 - Object-Oriented Programming: Inheritance

30

Putting Them 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 for the constructors

– 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 31: Chapter 12 - Object-Oriented Programming: Inheritance

31

class Time Specification

class Time{

public :

void Set ( int h, int m, int s ) ;void Increment ( ) ;void Write ( ) const ;Time ( int initH, int initM, int initS ) ; // constructor Time ( ) ; // default constructor

protected :

int hrs ; int mins ; int secs ;

} ;

// SPECIFICATION FILE ( time.h)

Page 32: Chapter 12 - Object-Oriented Programming: Inheritance

32

Class Interface Diagram

Protected data:

hrs

mins

secs

Set

Increment

Write

Time

Time

Time class

Page 33: Chapter 12 - Object-Oriented Programming: Inheritance

33

Derived Class ExtTime // 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 and use public inheritance

{ public :

void Set ( int h, int m, int s, ZoneType timeZone ) ;void Write ( ) const; //overridden

ExtTime (int initH, int initM, int initS, ZoneType initZone ) ; ExtTime (); // default constructor

private :ZoneType zone ; // added data member

} ;

Page 34: Chapter 12 - Object-Oriented Programming: Inheritance

34

Class Interface Diagram

Protected data:

hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data:zone

Page 35: Chapter 12 - Object-Oriented Programming: Inheritance

35

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 36: Chapter 12 - Object-Oriented Programming: Inheritance

36

Implementation of ExtTime

Another Constructor

ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer

{ zone = initZone ;}

ExtTime *et2 =

new ExtTime(8,30,0,EST);hrs = 8mins = 30secs = 0zone = EST

et2

5000

???

6000

5000

Page 37: Chapter 12 - Object-Oriented Programming: Inheritance

37

Implementation of ExtTime

void ExtTime :: Set (int h, int m, int s, ZoneType timeZone)

{

Time :: Set (hours, minutes, seconds); // same name function call

zone = timeZone ;

}

void ExtTime :: Write ( ) const // function overriding

{

string zoneString[8] =

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

Time :: Write ( ) ;

cout <<‘ ‘<<zoneString[zone]<<endl;

}

Page 38: Chapter 12 - Object-Oriented Programming: Inheritance

38

Working with ExtTime

#include “exttime.h”… …

int main() {

ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called

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

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

thisTime.Increment ( ) ;thisTime.Increment ( ) ;thisTime.Write ( ) ; // outputs 08:35:02 PST

}

Page 39: Chapter 12 - Object-Oriented Programming: Inheritance

39

Take Home Message

• Inheritance is a mechanism for defining new class types to be a specialization or an augmentation of existing types.

• In principle, every member of a base class is inherited by a derived class with different access permissions, except for the constructors

Page 40: Chapter 12 - Object-Oriented Programming: Inheritance

Example: Composition

class X

{

private:

int m_Data; // data member

public:

X() {} // default constructor

SetX (int k) // member function

{

m_Data = k;

}

};

class Y

{

private:

int m_Data;

Page 41: Chapter 12 - Object-Oriented Programming: Inheritance

Example: Composition (contd.)

public:

X x; // composition

Y() {} //default constructor

};

void main()

{

Y y; // creating object of class Y

y.x.SetX(20); // Access/sets the embedded object

}

Page 42: Chapter 12 - Object-Oriented Programming: Inheritance

12-42

Class hierarchy from a C++ implementation of the shape example

Page 43: Chapter 12 - Object-Oriented Programming: Inheritance

12-43

Adding a subclassAdd a new subclass of Shape to allow the treelike diagram: