Lecture 5 Inheritance

38
Lecture # 5 Lecture # 5 Inheritance Inheritance

Transcript of Lecture 5 Inheritance

Page 1: Lecture 5 Inheritance

Lecture # 5Lecture # 5

Inheritance Inheritance

Page 2: Lecture 5 Inheritance

► Inheritance is probably the most powerful Inheritance is probably the most powerful feature of object oriented programming feature of object oriented programming which is used in achieving which is used in achieving software software reusabilityreusability..

► Inheritance is the process of creating new Inheritance is the process of creating new classes, called classes, called derived classesderived classes from from existing or existing or base classesbase classes..

► The derived class inherits all the The derived class inherits all the capabilities of the base class but can add capabilities of the base class but can add its own functionalities and refinements.its own functionalities and refinements.

► Consider the following figure.Consider the following figure.

Page 3: Lecture 5 Inheritance

Arrow means “Derived from”

Function a

Function b

Function c

Function b

Function a

defined only in

derived class

Derived class (e.g. Horse )

Base class( e.g. Animal )

Page 4: Lecture 5 Inheritance

► Base class does not inherit any class.Base class does not inherit any class.► Derived class does inherit any other Derived class does inherit any other

class or classes.class or classes.► Single inheritanceSingle inheritance

►Derived class only Inherits from Derived class only Inherits from one base classone base class

► Multiple inheritanceMultiple inheritance►Derived class can Inherit from Derived class can Inherit from

multiple base classesmultiple base classes In this case base classes may be In this case base classes may be

possibly unrelated from real life possibly unrelated from real life point of viewpoint of view

Page 5: Lecture 5 Inheritance

““is-a” vs. “has-a” relationshipis-a” vs. “has-a” relationship ““is-a”is-a”

►InheritanceInheritance►Derived class object treated as base class Derived class object treated as base class

objectobject►Example: Car Example: Car is ais a vehicle vehicle

Car (derived class) inherits vehicle (base Car (derived class) inherits vehicle (base class)class)

““has-a”has-a”►CompositionComposition►Object contains one or more objects of other Object contains one or more objects of other

classes as membersclasses as members►Example: Car Example: Car has ahas a steering wheel steering wheel

( car and wheel are classes )( car and wheel are classes )

Page 6: Lecture 5 Inheritance

Base Classes and Derived Classes

Base class Derived classes

Student GraduateStudent UndergraduateStudent

Shape Circle Triangle Rectangle

Loan CarLoan HomeImprovementLoan MortgageLoan

Employee FacultyMember StaffMember

Account CheckingAccount SavingsAccount

Page 7: Lecture 5 Inheritance

Inheritance hierarchy for university Inheritance hierarchy for university Community Members.Community Members.

Single inheritance

CommunityMember

Employee Student

Administrator Teacher

AdministratorTeacher

StaffFaculty

Alumnus

Single inheritance

Single inheritance

Multiple inheritance

Page 8: Lecture 5 Inheritance

Shape

TwoDimensionalShape ThreeDimensionalShape

Circle Square Triangle Sphere Cube Tetrahedron

Inheritance hierarchy for Shapes.

Page 9: Lecture 5 Inheritance

► Base class Base class does notdoes not inherit any class. inherit any class.

► Derived class Derived class doesdoes inherit any other inherit any other class or classes.class or classes.

Page 10: Lecture 5 Inheritance

Example: InheritanceExample: Inheritance#include <conio.h>#include <conio.h>#include <iostream.h>#include <iostream.h>

class arithmaticclass arithmatic{{ protected :protected : int a,b;int a,b; public :public : void add(int x, int y)void add(int x, int y) {{ a=x;a=x; b=y;b=y; cout<<" \n Addition of a & b is : "<<a+b;cout<<" \n Addition of a & b is : "<<a+b; }}};};

Page 11: Lecture 5 Inheritance

class operation1 : public arithmaticclass operation1 : public arithmatic

{{

public :public :

void mul(int x, int y)void mul(int x, int y)

{{

a=x;a=x;

b=y;b=y;

cout<<" \n Multiplication of a & b cout<<" \n Multiplication of a & b is :”<<a*b;is :”<<a*b;

}}

};};

Page 12: Lecture 5 Inheritance

void main()void main(){{ operation1 op1;operation1 op1; int m,n;int m,n; cout<<" Enter number 1 :";cout<<" Enter number 1 :"; cin>>m;cin>>m; cout<<" Enter number 2 :";cout<<" Enter number 2 :"; cin>>n;cin>>n; op1.mul(m,n);op1.mul(m,n); op1.add(m,n);op1.add(m,n);

getch();getch();}}

Page 13: Lecture 5 Inheritance

Important Note:Important Note:

►One thing is to be noted that One thing is to be noted that whenever the object of derived class is whenever the object of derived class is created the constructor of created the constructor of bothboth, the , the derived derived and and basebase classes are called classes are called automatically.automatically.

Page 14: Lecture 5 Inheritance

Constructors and Constructors and Destructors in Derived ClassesDestructors in Derived Classes► Instantiating derived-class objectInstantiating derived-class object

Chain of constructor callsChain of constructor calls►Derived-class constructor invokes base Derived-class constructor invokes base

class constructorclass constructor Implicitly or explicitlyImplicitly or explicitly

►Base class of inheritance hierarchyBase class of inheritance hierarchy Last constructor called in chainLast constructor called in chain First constructor body to finish executingFirst constructor body to finish executing

►Initializing data membersInitializing data members Each base-class constructor initializes data Each base-class constructor initializes data

membersmembers► Inherited by derived classInherited by derived class

Page 15: Lecture 5 Inheritance

►Destroying derived-class objectDestroying derived-class object Chain of destructor callsChain of destructor calls

►Reverse order of constructor chainReverse order of constructor chain►Destructor of derived-class called firstDestructor of derived-class called first►Destructor of next base class up Destructor of next base class up

hierarchy nexthierarchy next Continue up hierarchy until final base reachedContinue up hierarchy until final base reached

► After final base-class destructor, object After final base-class destructor, object removed from memoryremoved from memory

Page 16: Lecture 5 Inheritance

protectedprotected Access Specifier Access Specifier

►A protected member can be accessed A protected member can be accessed by member functions in its own class by member functions in its own class oror

► In any class derived from its own class.In any class derived from its own class.

► It cannot be accessed from functions It cannot be accessed from functions outside these classes such as outside these classes such as main( )main( ) function.function.

Page 17: Lecture 5 Inheritance

► The moral is that if you are writing a The moral is that if you are writing a class that you suspect might be used at class that you suspect might be used at any point in the future, as a base class any point in the future, as a base class for other classes, then any functions or for other classes, then any functions or data that the derived class might need data that the derived class might need to access should be made protected to access should be made protected rather than private. This ensures that rather than private. This ensures that class is “class is “Inheritance ReadyInheritance Ready”. ”.

► Table summarizes the above situation Table summarizes the above situation as follows.as follows.

Page 18: Lecture 5 Inheritance

► Inheritance and AccessibilityInheritance and Accessibility

Access Access SpecifieSpecifierr

AccessibAccessible from le from own own classclass

AccessibAccessible from le from derived derived classclass

Accessible Accessible from from objects objects outside outside classclass

publicpublic yesyes yesyes yesyes

protecteprotecte

dd

yesyes yesyes nono

privateprivate yesyes nono nono

Page 19: Lecture 5 Inheritance

Overriding member Overriding member functionsfunctions

Page 20: Lecture 5 Inheritance

►You can use member functions in a You can use member functions in a derived derived class that have the same class that have the same name as those in the name as those in the basebase class. class.

►You might want to do this so that You might want to do this so that calls in your program work the calls in your program work the same way for objects of both base same way for objects of both base and derived classes.and derived classes.

Page 21: Lecture 5 Inheritance

Example: function Example: function overridingoverriding#include <conio.h>#include <conio.h>

#include <iostream.h>#include <iostream.h>class arithmaticclass arithmatic{{

protected :protected : int a,b;int a,b; public :public : void add(int x, int y)void add(int x, int y) {{ a=x;a=x; b=y;b=y; cout<<" \n Addition of a & b is : cout<<" \n Addition of a & b is :

"<<(a+b);"<<(a+b); }}};};

Page 22: Lecture 5 Inheritance

class operation1 : public arithmaticclass operation1 : public arithmatic

{{

public :public :

void add(int x, int y)void add(int x, int y)

{{

cout<<"\n Derived class add function cout<<"\n Derived class add function called.\n";called.\n";

arithmatic :: add(x,y);arithmatic :: add(x,y);

}}

};};

Page 23: Lecture 5 Inheritance

void main()void main(){{ operation1 op1;operation1 op1; arithmatic arith1;arithmatic arith1; int m,n;int m,n; cout<<" Enter number 1 :";cout<<" Enter number 1 :"; cin>>m;cin>>m; cout<<" Enter number 2 :";cout<<" Enter number 2 :"; cin>>n;cin>>n; op1.add(m,n);op1.add(m,n); cout<<"\n**************************\n";cout<<"\n**************************\n"; arith1.add(m,n);arith1.add(m,n); getch();getch();}}

Page 24: Lecture 5 Inheritance

► The arithmatic and operation1 classes The arithmatic and operation1 classes has same functions with the has same functions with the namename, the , the same same argumentsarguments and same and same return return typetype..

► When we call the function from main() as When we call the function from main() as op1.add(m,n);op1.add(m,n); how does the compiler how does the compiler know which function to follow?know which function to follow?

► Answer is when the same function(s) Answer is when the same function(s) exists in both the base and derived class, exists in both the base and derived class, the function in the derived class will be the function in the derived class will be executed.executed.

Page 25: Lecture 5 Inheritance

►Objects of the base class donot Objects of the base class donot know anything about the derived know anything about the derived class and will always use the base class and will always use the base class functions as in program the class functions as in program the call : call : arith1.add(m,n); arith1.add(m,n);

►When the functions with the same When the functions with the same name appears in name appears in basebase and and derivedderived classes we say that classes we say that derived class function derived class function overridesoverrides the base class function.the base class function.

Page 26: Lecture 5 Inheritance

Multiple InheritanceMultiple Inheritance

Page 27: Lecture 5 Inheritance

►A class can be derived from more A class can be derived from more than one base class. This is called than one base class. This is called multiple inheritance.multiple inheritance.

►Figure shows the above comment.Figure shows the above comment.

Base class ABase class A Base class BBase class B

Derived class C

Page 28: Lecture 5 Inheritance

►The syntax for multiple inheritance The syntax for multiple inheritance is similar to that for single is similar to that for single inheritance. The above figure inheritance. The above figure relationship is expressed like this : relationship is expressed like this :

class A // Base Class Aclass A // Base Class A {{ };};class Bclass B // Base Class B// Base Class B {{ };};class C : public A, public B // C is derived from class C : public A, public B // C is derived from

A and BA and B {{ };};

Page 29: Lecture 5 Inheritance

Example: Multiple Example: Multiple InheritanceInheritance#include <conio.h>#include <conio.h>

#include <iostream.h>#include <iostream.h>class operation1class operation1{{

protected :protected : int a,b;int a,b; public :public : void add(int x, int y)void add(int x, int y) {{ a=x;a=x; b=y;b=y; cout<<" \n Addition of a & b is : cout<<" \n Addition of a & b is :

"<<(a+b);"<<(a+b); }}};};

Page 30: Lecture 5 Inheritance

class operation2class operation2{{

protected :protected : int a,b;int a,b; public :public : void sub(int x, int y)void sub(int x, int y) {{ a=x;a=x; b=y;b=y; cout<<" \n subtraction of a & b cout<<" \n subtraction of a & b

is : "<<(a-b);is : "<<(a-b); }}};};

Page 31: Lecture 5 Inheritance

class arithmatic : public operation1, public class arithmatic : public operation1, public operation2operation2

{{ private :private : int a,b;int a,b; public :public : void mul(int x, int y)void mul(int x, int y) {{ a=x;a=x; b=y;b=y; cout<<" \n Multiplication of a & cout<<" \n Multiplication of a &

b is : "<<a*b;b is : "<<a*b; }}};};

Page 32: Lecture 5 Inheritance

void main()void main(){{ arithmatic arith1;arithmatic arith1; int m,n;int m,n; cout<<" Enter number 1 :";cout<<" Enter number 1 :"; cin>>m;cin>>m; cout<<" Enter number 2 :";cout<<" Enter number 2 :"; cin>>n;cin>>n; arith1.mul(m,n);arith1.mul(m,n); arith1.add(m,n);arith1.add(m,n); arith1.sub(m,n);arith1.sub(m,n); getch();getch();}}

Page 33: Lecture 5 Inheritance

► In the above program In the above program arithmaticarithmatic class class inherits two other classes i.e. inherits two other classes i.e. operation1operation1 and and operation2operation2 as follows : as follows :

class arithmatic : public operation1, class arithmatic : public operation1, public operation2public operation2

► operation1operation1 class implements addition class implements addition and and operation2operation2 class implements class implements subtraction subtraction

WhileWhile► arithmaticarithmatic class implements class implements

multiplication which inherits already multiplication which inherits already made classes for addition and made classes for addition and subtraction.subtraction.

Page 34: Lecture 5 Inheritance

What are the possible alternatives to What are the possible alternatives to implement division operation (function) in implement division operation (function) in

the previous approach of multiple the previous approach of multiple inheritance. Give at least two alternatives?inheritance. Give at least two alternatives?

Page 35: Lecture 5 Inheritance

Ambiguity in Multiple Ambiguity in Multiple InheritanceInheritance

► Consider the scenario(situation) if two Consider the scenario(situation) if two base classes have functions with the base classes have functions with the same name, while a class derived from same name, while a class derived from both base classes has no function with both base classes has no function with this name.this name.

► How do objects of the derived class How do objects of the derived class access the correct base class function?access the correct base class function?

► The name of the function alone is The name of the function alone is insufficient, since the compiler cannot insufficient, since the compiler cannot figure out which of the two functions are figure out which of the two functions are meant. Next example demonstrates this meant. Next example demonstrates this situation.situation.

Page 36: Lecture 5 Inheritance

class Aclass A{{

public :public : void show(int x, int y)void show(int x, int y)

{ cout<<“\n Class A :”; }{ cout<<“\n Class A :”; }};};class Bclass B{{

public :public : void show(int x, int y)void show(int x, int y) { cout<<“\n Class B :”; }{ cout<<“\n Class B :”; }};};class C : public A, public Bclass C : public A, public B{{};};

Page 37: Lecture 5 Inheritance

void main()void main(){{ C obj;C obj;obj.show( ); obj.show( ); // Ambiguous statement--- will not // Ambiguous statement--- will not

compilecompile obj.A :: show( );obj.A :: show( );obj.B :: show( );obj.B :: show( );getch();getch();}}► The problem is resolved using the scope –resolution The problem is resolved using the scope –resolution

operator to specify the class in which the function lies. operator to specify the class in which the function lies. Thus Thus obj.A :: show( );obj.A :: show( );refers to the version of show( ) that is in the A class refers to the version of show( ) that is in the A class whilewhileobj.B :: show( );obj.B :: show( );refers to the function show( ) that is in the B class.refers to the function show( ) that is in the B class.

► The scope resolution operator resolved the ambiguity The scope resolution operator resolved the ambiguity and the compiler is happy now.and the compiler is happy now.

Page 38: Lecture 5 Inheritance

ThanXX…ThanXX…