Inheritance concepts

124
CM505.36 1 OBJECTIVE On completion of this period, you would be able to know Necessity of Inheritance Relation between base class and derived class

Transcript of Inheritance concepts

Page 1: Inheritance concepts

CM505.36 1

OBJECTIVE

On completion of this period, you would be able to know

• Necessity of Inheritance • Relation between base class and derived class

Page 2: Inheritance concepts

CM505.36 2

Inheritance

Acquiring the properties of one class to another

class is inheritance.

Page 3: Inheritance concepts

CM505.36 3

Necessity for inheritance

• Reusability

• We can derive a new class from an existing one and add new features to it.

Page 4: Inheritance concepts

CM505.36 4

Necessity for inheritance

• Another major reason for inheriting is the capability to express the inheritance relationship which ensure the closeness with the real world.

• And one of the other reason is transitive nature.

Page 5: Inheritance concepts

CM505.36 5

Relation between base class & derived class

• Inheritance is the process of creating a new class called derived class from the existing class called base class.

• The derived class inherits all the capabilities of the base class.The base class remains unchanged.

Page 6: Inheritance concepts

CM505.36 6

Relation between base class and derived class

Feature A

Feature B

Feature C

Feature B

Feature C

Feature A

Feature D

Base Class(Existing Class)

Derived Class(New Class)

Defined In

Derived class

Derived in baseClass and alsoAccessible fromDerived class

Fig .1

Page 7: Inheritance concepts

CM505.36 7

Relation between base class and derived class

• The derived class inherits the features of the base

class A, B and C and adds its own features D.

• The arrow in the diagram symbolizes derived from.

Page 8: Inheritance concepts

CM505.36 8

Relation between base class and derived class

• A base class is also called

• parent class or

• super class

• A derived class is also called

• child class or

• subclass.

• A derived class may itself be base class from

which the additional classes are derived.

Page 9: Inheritance concepts

CM505.36 9

Relation between base class and derived class

DERIVED CLASS:

• The declaration of derived class is as that same of ordinary class.

• A derived class contains of the following components

Page 10: Inheritance concepts

CM505.36 10

Relation between base class and derived class

DERIVED CLASS: • The keyword class

• The name of the Derived class

• A single colon

Page 11: Inheritance concepts

CM505.36 11

Relation between base class and derived class

DERIVED CLASS:• The type of derivation (private, public or

protected)

• The name of the base or parent class

• The reminder of the class definition

Page 12: Inheritance concepts

CM505.37to38 12

Access control or

visibility mode: The three types of access control or visibility modes are:

• public

• private

• protected

Pre requisite

Page 13: Inheritance concepts

CM505.37to38 13

Syntax for defining a derived class

Syntax:

class derived_classname : visibilitymode base_classname

{

……………… ……………… Members of derived class

};

Page 14: Inheritance concepts

CM505.37to38 14

Relation between base class and derived class

Syntax: class derived_classname : visibilitymode base_classname

{ ……………… ……………… Members of derived class } ;

Page 15: Inheritance concepts

CM505.37to38 15

Syntax for defining a derived class

• The colon indicates that the derived class name is derived from the base class name.

• The visibility mode is optional.i.e it may be public or private.

• The default visibility mode specifies the features are private.

contd..

Page 16: Inheritance concepts

CM505.37to38 16

Syntax for defining a derived class

Example: class A { ………………….}members of base class A }; class x : public A { ……………}members of derived class X };

contd..

Page 17: Inheritance concepts

CM505.37to38 17

Access control or visibility mode

The three types of access control or visibility modes are:

• public

• private

• protected

Page 18: Inheritance concepts

CM505.37to38 18

Access control or visibility mode

Public:

• The public derivation means that the derived class can access the public and protected members of the base class but not the private members of base class

contd..

Page 19: Inheritance concepts

CM505.37to38 19

Access control or visibility mode

Public:

• The public members of the base class becomes public members of the derived access specified for inherited members in the derived class.

contd..

Page 20: Inheritance concepts

CM505.37to38 20

Access control or visibility mode

Public Member of a class:

• The members of a class, which are to be visible outside the class .

• Public members should be declared in public section only.

contd..

Page 21: Inheritance concepts

CM505.37to38 21

Access control or visibility mode

Public Member of a class:• All the members and functions can be

declared in public section

• they can be accessed without any restriction from any where in the program.

contd..

Page 22: Inheritance concepts

CM505.37to38 22

Access control or visibility mode

Public Member of a class:• Either by function that belong to the class or

by those external to the class.

contd..

Page 23: Inheritance concepts

CM505.37to38 23

Access control or visibility mode

Public Member of a class

Example: class person { public: int age; int get age() { } };

contd..

Page 24: Inheritance concepts

CM505.37to38 24

Access control or visibility mode

Private:

The private derivation means that the derived class can access the public and protected members of the base class.

contd..

Page 25: Inheritance concepts

CM505.37to38 25

Access control or visibility mode

Private:• The public, protected members of the

base class becomes private members of derived class.

• i.e the inheritance becomes private in the derived class.

• They cannot be inherited further.

contd..

Page 26: Inheritance concepts

CM505.37to38 26

Access control or visibility mode

Private Member of a class:

• The private member of a class have strict access control.

• Only the member functions of the same class can access these members.

• The private members of a class are inaccessible outside the class.

contd..

Page 27: Inheritance concepts

CM505.37to38 27

Access control or visibility mode

Private Member of a class:

• Thus providing a mechanism for preventing

accidental modifications of the data members.

• Information hidden is implemented.

• The private members can still accessed.

contd..

Page 28: Inheritance concepts

CM505.37to38 28

Access control or visibility mode

Private Member of a class:

• Access control in c++ has objective of reducing the likelihood of bugs and enhancing consistency.

contd..

Page 29: Inheritance concepts

CM505.37to38 29

Access control or visibility mode

Private Member of a class:

• The class should have at least one member

that is not private.

contd..

Page 30: Inheritance concepts

CM505.37to38 30

Access control or visibility mode

Private Member of a class:Example: class person { private: int age; int get age() { } };

contd..

Page 31: Inheritance concepts

CM505.37to38 31

Access control (or) visibility mode Protected: • The protected derivation means that the

derived class can access the public and private members of the base class.

• public protected numbers the base class become protected numbers in the derived class.

contd..

Page 32: Inheritance concepts

CM505.37to38 32

Access control (or) visibility mode

Protected Member of a class : • The access control of the members is similar

to that of private members.

• Protected members has more significance ininheritance.

contd..

Page 33: Inheritance concepts

CM505.37to38 33

Access control (or) visibility mode

Protected Member of a class:

• The protected members of a class have strict access these members.

• Providing a mechanism for preventing accidental modifications of the data members.

contd..

Page 34: Inheritance concepts

CM505.37to38 34

Access control (or) visibility mode

Protected Member of a class:• Only the member functions of same class

can access these members.

• The protected members of a class are inaccessible outside the class.

contd..

Page 35: Inheritance concepts

CM505.37to38 35

Access control (or) visibility mode

Protected Member of a class: • Information hiding is implemented.

• The protected members can still be accessed.

contd..

Page 36: Inheritance concepts

CM505.37to38 36

Access control (or) visibility mode

Protected Member of a class:

Example: class person { protected: int age; int get age() { } };

contd..

Page 37: Inheritance concepts

CM505.37to38 37

Access control (or) visibility mode

Inheritance type case class derived class

private

public

protected

private numbers public numbers

Protected numbers

private numberspublic numbersprotected numbers

private numbers

protected numberspublic numbers

not inheritedprivate numbers

private numbers

not inheritedpublic numbersprotected numbers

not inheritedprotected numbers

protected numbers

contd..

Page 38: Inheritance concepts

CM505.39 38

Inheritance

The inheritance is classified as

• Single inheritance

• Multiple inheritance

• Multilevel inheritance

• Hierarchical inheritance

• Hybrid inheritance

Page 39: Inheritance concepts

CM505.39 39

Inheritance

Single inheritance: • A single inheritance contains only one derived

class and one base class.

Page 40: Inheritance concepts

CM505.39 40

Single Inheritance

BASE CLASS

DERIVED CLASS

Page 41: Inheritance concepts

CM505.39 41

Multi level inheritance

• more than one level of inheritance

base class

Derived class

Derived class

level/1

level/2

Page 42: Inheritance concepts

CM505.39 42

Multiple Inheritance

A derived class with several base

classes is known as multiple inheritance.

Page 43: Inheritance concepts

CM505.39 43

BASE CLASS 1 BASE CLASS 2

DERIVED CLASS

Multiple Inheritance

Page 44: Inheritance concepts

CM505.39 44

Hierarchical Inheritance

The properties of one class may be inheritance by more than one class. This process is known as Hierarchical Inheritance.

Page 45: Inheritance concepts

CM505.39 45

BASE CLASS

DERIVED CLASS DERIVED CLASS DERIVED CLASS

Hierarchical Inheritance

Page 46: Inheritance concepts

CM505.39 46

Hybrid Inheritance

The combination of multilevel & multiple inheritance is know as hybrid inheritance.

Page 47: Inheritance concepts

CM505.39 47

BASE CLASS 1

DERIVED CLASS1

DERIVED CLASS2

BASE CLASS 2

Hybrid Inheritance

Page 48: Inheritance concepts

48

Types of Derivation

• The class can be derived in three visibility modes

• public• private• protected

Page 49: Inheritance concepts

49

Public Derivation

• When a class is derived in the public mode it does not change the mode of the inherited members in the derived class. The public members remain public and protected members remain protected for the derived class in public inheritance.

Page 50: Inheritance concepts

50

Private Derivation

• When a class is derived in the private mode it changes the mode of the inherited members in the derived class. The public and protected members become the private members for the derived class. So the inherited members can be accessed only through the member functions of the derived class.

Page 51: Inheritance concepts

51

Protected Derivation

• When a class is derived in protected mode it changes the mode of the inherited members in the derived class. The public and protected members become the protected members for the derived class in protected inheritance. So the inherited members can be accessed only through the member functions of the derived class.

Page 52: Inheritance concepts

52

C++ Syntax: public derivation

class DerivedClass: public BaseClass

{

private: int y;

public:void setY(int y_in)

{y=y_in;}

int getY(){cout<<y;}

}

A derived class.The colon operator means

the derived classinherits from

the base class

Page 53: Inheritance concepts

53

C++ Syntax: public derivation

class DerivedClass: public BaseClass

{

private:

int y;

public:

void setY(int y_in)

{y=y_in;}

int getY()

{cout<<y;}

}

the public derivation means that objects of the derived classcan access the public methodsand attributes of the base class

This is the most usual typeof derivation

Page 54: Inheritance concepts

54

C++ Syntax: public derivation

class BaseClass

{

private:

int x;

public:

void setX(int x_in) {x=x_in;}

int getX() {cout<<x;}

}

class DerivedClass: public BaseClass

{

private:

int y;

public:

void setY(int y_in){y=y_in;}

int getY(){cout<<y;}

}

main(){BaseClass base_object;DerivedClass derived_object;

base_object.setX(7);

derived_object.setX(12);derived_object.setY(1);base_object.getX();derived_object.getY();derived_object.getX();return 0;}

Object of the derivedclass can access methods

of the derived classand also methods of the

base class

Page 55: Inheritance concepts

55

C++ Syntax: private derivation

• class DerivedClass: private BaseClass• {• private:

– int y;• public:

– void setY(int y_in);– int getY();

• }

Another derived class - the privatederivation means that objects

of the derived class can’taccess the public methods andattributes of the base class - butthe methods of the derived class

can!This is the least common type

Page 56: Inheritance concepts

56

C++ Syntax: the ‘protected’ keyword

• An object of a publicly derived class can access the public methods of the base class, but not the private attributes

• Changing the private keyword in the base class to protected makes the attributes available to derived classes

Page 57: Inheritance concepts

57

Access Specifiers

Access Specifier

Accessible from own class

Accessible from derived class

Accessible from objects from outside the class

public Yes Yes Yes

protected Yes Yes No

private Yes No No

Page 58: Inheritance concepts

58

Effect of inheritance on the visibility of member

Page 59: Inheritance concepts

59

C++ Syntax: inheriting destructors

• Constructors are not inherited. They are called implicitly or explicitly by the child constructor.

• The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type).

• But if we want a constructor that will accept an int, we have to define it explicitly

Page 60: Inheritance concepts

CM505.39 60

Advantages of Inheritance

• When one class is inherited from another class the code that provides a behavior required in the derived class need not have to be rewritten that is code be reused which increases reliability.

Page 61: Inheritance concepts

CM505.39 61

Advantages of Inheritance

• Code sharing can occur at several levels. • For example, • At a higher level , many users can use the

same class.

• At lower level, code can be shared by two or more classes.

Page 62: Inheritance concepts

CM505.39 62

Advantages of Inheritance

• When multiple classes inherit from the same base class, it guarantees that the behavior they inherit will be the same in all classes.

Page 63: Inheritance concepts

CM505.39 63

Advantages of Inheritance

• Inheritance permits the construction of

reusable software components.

• Using inheritance one can concentrate on understanding the portion of the new system.

Page 64: Inheritance concepts

CM505.39 64

Advantages of Inheritance

• The development time in developing a system will be reduced rapidly.

Page 65: Inheritance concepts

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 65

Page 66: Inheritance concepts

CPS235:Inheritance 66

Page 67: Inheritance concepts

CPS235:Inheritance 67

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 68: Inheritance concepts

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 69: Inheritance concepts

CPS235:Inheritance 69

Inheritance Concept

RectangleTriangle

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 70: Inheritance concepts

CPS235:Inheritance 70

RectangleTriangle

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 71: Inheritance concepts

CPS235:Inheritance 71

RectangleTriangle

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 72: Inheritance concepts

CPS235:Inheritance 72

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 73: Inheritance concepts

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 73

Page 74: Inheritance concepts

CPS235:Inheritance 74

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 75: Inheritance concepts

What to Inherit?

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

CPS235:Inheritance 75

Page 76: Inheritance concepts

CPS235:Inheritance 76

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 77: Inheritance concepts

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 77

Page 78: Inheritance concepts

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 C

on

trol

for M

emb

ers

Page 79: Inheritance concepts

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 79

Page 80: Inheritance concepts

CPS235:Inheritance 80

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 81: Inheritance concepts

CPS235:Inheritance 81

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 82: Inheritance concepts

CPS235:Inheritance 82

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 83: Inheritance concepts

CPS235:Inheritance 83

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 84: Inheritance concepts

CPS235:Inheritance 84

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 85: Inheritance concepts

CPS235:Inheritance 85

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 86: Inheritance concepts

CPS235:Inheritance 86

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 87: Inheritance concepts

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 88: Inheritance concepts

Encapsulation

class 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 89: Inheritance concepts

Encapsulation

class 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 90: Inheritance concepts

Encapsulation

class 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 91: Inheritance concepts

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 91

Page 92: Inheritance concepts

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 92

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 93: Inheritance concepts

Constructor Rules for Derived Classes

• You can also specify a constructor of the base class other than the default constructor

DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args )

{ DerivedClass constructor body }

CPS235:Inheritance 93

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 94: Inheritance concepts

CPS235:Inheritance 94

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 95: Inheritance concepts

Constructor Rules for Derived Classes

• Base constructor is called before the derived class constructor

• Destructors vice versa

CPS235:Inheritance 95

Page 96: Inheritance concepts

Calling the Base Class constructor

class 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 97: Inheritance concepts

Calling the Base Class constructor

class 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 98: Inheritance concepts

CPS235:Inheritance

98

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 99: Inheritance concepts

CPS235:Inheritance 99

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 100: Inheritance concepts

CPS235:Inheritance 100

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 101: Inheritance concepts

Public

CPS235:Inheritance 101

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 102: Inheritance concepts

CPS235:Inheritance 102

Time class example

Page 103: Inheritance concepts

CPS235:Inheritance 103

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 104: Inheritance concepts

CPS235:Inheritance 104

Class Interface Diagram

Protected data:

hrs

mins

secs

Set

Increment

Write

Time

Time

Time class

Page 105: Inheritance concepts

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 105

Page 106: Inheritance concepts

CPS235:Inheritance 106

Class Interface Diagram

Protected data:

hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data: zone

Page 107: Inheritance concepts

CPS235:Inheritance 107

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 108: Inheritance concepts

CPS235:Inheritance 108

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 109: Inheritance concepts

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 109

Page 110: Inheritance concepts

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 110

Page 111: Inheritance concepts

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 111

Page 112: Inheritance concepts

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 112

Page 113: Inheritance concepts

Ambiguities in Multiple Inheritance

• See code examples

CPS235:Inheritance 113

Page 114: Inheritance concepts

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 114

Page 115: Inheritance concepts

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 115

A class cannot be referred to until it has been declared

Page 116: Inheritance concepts

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 116

Page 117: Inheritance concepts

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 117

Page 118: Inheritance concepts

friend classes

class 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 118

Page 119: Inheritance concepts

friend classes

void main(){

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

CPS235:Inheritance 119

Page 120: Inheritance concepts

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 120

Page 121: Inheritance concepts

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 121

Page 122: Inheritance concepts

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 122

Page 123: Inheritance concepts

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 capabilitiesCPS235:Inheritance 123

Page 124: Inheritance concepts

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 124