Inheritance

80
1 Inheritance

description

 

Transcript of Inheritance

Page 1: Inheritance

1

Inheritance

Page 2: Inheritance

2

IntroductionInheritance is a way of creating a new class by starting with an existing class and adding new members.The technique of building new classes from the existing classes is called inheritance.The new class can replace or extend the functionality of the existing class.The old class remains as it was.

Page 3: Inheritance

3

Cont…Base Class : The existing class is called the. Also known as parent class or super-class.

Derived class: Class that inherits data members and

member functions from a previously defined base class.

Also known as child class or subclass. It has capabilities of the base class and can

add refinements and extensions of its own.

Page 4: Inheritance

4

Cont…We can program without inheritance (a hierarchy) as we have done so far. That is known as object based programming.

Programming using inheritance is known as object oriented programming.

Page 5: Inheritance

5

Cont…Some real-world relationships/hierarchies using inheritance: mammal a class from Living things. People a class derived from Mammal. Man and woman classes derived from People. Indian People class derived from People.

Page 6: Inheritance

6

Cont…Benefit of Inheritance:

It provides the feature of code reusability. Once a base class is written and debug then

further it can be used anywhere in the program with some other features.

It save time and increases program reliability.

We would like to model a real-world hierarchy in our program in a natural way.

Page 7: Inheritance

7

Cont…We can have multiple classes with some attributes common to them. We would like to avoid problems of inconsistencies between the common attributes.

Page 8: Inheritance

8

Inheritance Syntax

// Existing class class <Base_class> { };

// new class class <Derived_class> : <visibility_mode> <Base_class>

{ };

Page 9: Inheritance

9

Example

// Existing class class Base { };

// Derived class class Derived : public Base { };

Inheritance Class

DiagramBase Class

Derived Class

Page 10: Inheritance

10

Base Class Access Specification

It determines how private, protected, and public members of base class can be accessed by derived classes.

Page 11: Inheritance

11

Base Class Access Modes

C++ supports three inheritance modes, also called base class access modes or visibility modes :

public inheritance protected inheritance private inheritance

Page 12: Inheritance

12

Cont…Public Derived objects are accessible by the base

class objects.

Private Derived objects are inaccessible by the base

class.

Protected Derived classes and friends can access

protected members of the base class.

(will be discussed later)

Page 13: Inheritance

13

Cont… class child : public Parent

{ };

class Child : protected Parent{ };

class Child : private Parent{ };

Page 14: Inheritance

14

Cont…

Note : Private members of base class can never be inherited by derived class.

Page 15: Inheritance

15

Cont… : Public Mode

In Public mode is used to derive the new class publicly from the base class.

The protected members of base class become the protected members of derived class.

The public members of base class become the public members of derived class.

Page 16: Inheritance

16

Cont… : Protected Mode

The protected and public members of base class become the protected members of the derived class. Can be further inherited by another derived

class (in multilevel inheritance).

Page 17: Inheritance

17

Cont… : Private mode

The protected and public members of base class become the private members of derived class. Now these members can not be further

inherited.

Page 18: Inheritance

18

Protected and private members

Protected members are similar to private members except that Private members can never be inherited but

protected members can be inherited.

Protected members are accessible by the member functions within its class and any class immediately derived from it. It cannot be accessed by the functions outside

these two classes.

Page 19: Inheritance

19

Cont…

The friend functions and the member function of a class that is a friend of the class can have direct access to both the private and protected data.

Page 20: Inheritance

20

Private

protected

public

Private

protected

public

Private

protected

publicPrivate

protected

public

Base class

Derived classPrivate mode

Derived classProtected mode

Derived ClassPublic mode

Page 21: Inheritance

21

Examples : Private modeClass A{Private :

int i; void fun1() { }

Protected : int j;void fun2() { }

Public : int k;void fun3() { }

};

Class B : private A{Private :

int a; void fun4() { }

Protected : int b;void fun5() { }

Public : int c;void fun6() { }

};

Page 22: Inheritance

22

Cont…Members of class B: Private members:

Member variables : A, j, kMember functions: fun4, fun2, fun3

Protected members:Member variables : bMember functions : fun5

Public members:Member variables : cMember functions : fun6

Page 23: Inheritance

23

Examples : Protected modeClass A{Private :

int i; void fun1() { }

Protected : int j;void fun2() { }

Public : int k;void fun3() { }

};

Class B : protected A{Private :

int a; void fun4() { }

Protected : int b;void fun5() { }

Public : int c;void fun6() { }

};

Page 24: Inheritance

24

Cont…Members of class B: Private members:

Member variables : AMember functions: fun4

Protected members:Member variables : b, j, k Member functions : fun5, fun2, fun3

Public members:Member variables : cMember functions : fun6

Page 25: Inheritance

25

Examples : Public modeClass A{Private :

int i; void fun1() { }

Protected : int j;void fun2() { }

Public : int k;void fun3() { }

};

Class B : public A{Private :

int a; void fun4() { }

Protected : int b;void fun5() { }

Public : int c;void fun6() { }

};

Page 26: Inheritance

26

Cont…Members of class B: Private members:

Member variables : aMember functions: fun4

Protected members:Member variables : b, jMember functions : fun5, fun2

Public members:Member variables : c, kMember functions : fun6, fun3

Page 27: Inheritance

27

Types of Inheritance

Single level inheritanceMultiple level inheritanceMultilevel inheritanceHierarchical inheritanceHybrid inheritance

Page 28: Inheritance

28

Single level inheritance

It consists of a single base class and a single derived class.

A

B

Base Class

Derived class

Page 29: Inheritance

29

Multiple level inheritance

It consists of a derived class with more than one base class.

A

C

Base Class

Derived class

B

Page 30: Inheritance

30

Multilevel inheritanceIt consists of derived class of a base class, which behaves as a base class for its another derived class.

A

B

Base Class

Derived class of A and Base class of C

C Derived class of B

Page 31: Inheritance

31

Cont…

Multilevel inheritance also leads to direct base class and indirect base class.

Direct base class Explicitly listed derived class’ header with the colon

(:) notation when that derived class is declared. class HourlyWorker : public Employee

Employee is a direct base class of HourlyWorker

Indirect base class Inherited from two or more levels up the class

hierarchy class MinuteWorker : public HourlyWorker

Employee is an indirect base class of MinuteWorker

Page 32: Inheritance

32

Hierarchical inheritance

It consists of more than one class that are derived from a single base class.

C

A Base Class

Derived classB

Page 33: Inheritance

33

Hybrid inheritance

It can be a mixture of any two other levels of inheritance.

A

B C

D

A

B

C E

F

Page 34: Inheritance

34

Some examples of base and derived classesAn Inheritance hierarchy for university community members:

Page 35: Inheritance

35

A portion of a shape class hierarchy:

Page 36: Inheritance

36

Accessibility

When objects of derived class access the base class members automatically then it is called accessibility.

Page 37: Inheritance

37

Calling functions from derived class:

When a function name with the object of derived class is called,

Compiler searches in the derived class. If found, it executes.

Otherwise, searches in the base class. If found in the base class, executes. Otherwise, generates error.

Page 38: Inheritance

38

Cont…: Example 1Class A{};

Class B : public A{Public :

void display() { }

};

Void main(){B ob;Ob.display (); //calls

function of class B}

Page 39: Inheritance

39

Cont…: Example 2Class A{Public :

void display(){ }

};

Class B : public A{};

Void main(){B ob;Ob.display (); //calls

function of class A}

Page 40: Inheritance

40

Cont…

If both derived and base class contains the functions with the same name: Priority is to the function of derived class.

Known as function Overriding.

Priority can be changed as per the requirements.

Page 41: Inheritance

41

Cont…: Example 3

Class A{Public :

void display(){ }

};

Class B : public A{Public :

void display(){ }

};

Page 42: Inheritance

42

Cont…

Void main(){B ob;Ob.display(); //calls function of class

B}

Page 43: Inheritance

43

Cont…

To forcefully call the member functions of base class even when already present in derive class, use Base_class_name :: function_name ();

Page 44: Inheritance

44

Cont…: Example 4

Class A{Public :

void display(){ }

};

Class B : public A{Public :

void display(){ }

};

Page 45: Inheritance

45

Cont…Void main(){B ob;Ob.display(); //calls function of class

BOb.A::display(); // calls function of A}

Page 46: Inheritance

46

ExerciseWrite a program to create a base class “Data” which has two private member int a and int b and has one protected member char op. The class has some public methods as further requirements.

Create a derived class “Calculator” from the base class “Data”. The derived class has one private member float result.

Consider appropriate method in the derived class and perform the activity of calculator (add, subtract, multiply, divide) and display the result.

Use public derivation. Use private derivation.

Page 47: Inheritance

47

Example of Multilevel Inheritance:Class Person {Char *name;Int age;Public:

void getdata() { }void display () { }

};

Class Employee : public Person

{Int emp_id;Int salary;Public:

void getemp() { }void dispemp () { }

};

Page 48: Inheritance

48

Class Faculty : public Employee

{Char *area_of_interest;Public:

void get_Int () { }void disp_Int () { }

};

Void main(){

Faculty f;f.getdata();f.getemp();f.get_Int();

f.display ();f.dispemp ();f.disp_Int();

}

Page 49: Inheritance

49

Cont…Base class is Person, derived by Employee class.

Employee class is the intermediate base class of Faculty (a derived class).

This chain is known as inheritance path: Person Employee Faculty

Page 50: Inheritance

50

Cont…Faculty class has the accessibility to all the methods of Employee and Person classes.

Accessibility depends upon the visibility of base classes.

Page 51: Inheritance

51

Example of Multiple Inheritance:Class Student {Char *name;char dob[10];Public:

void getdata () { }void display () { }

};

Class SportsPerson{Char *result;Public:

void getResult () { }void dispResult () { }

};

Page 52: Inheritance

52

Class SportsStudent : public Student, public SportsPerson

{Public:

void get () {getdata();getResult(); }void disp () {

display();dispResult();

}};

Void main(){

SportsStudent s;s.getdata();s.display ();

}

Page 53: Inheritance

53

Cont…SportsStudent is the derived class, inherited from two base classes – Student and SportsPerson.

SportsStudent can access all the functions of both base classes.

There can be more than two base classes.

Page 54: Inheritance

54

Cont…: Ambiguity resolution in Inheritance

Ambiguity : If both derived and base class contains the function with same name, which function should be accessed?

Solution is Use the scope of the required class with the function name.

Page 55: Inheritance

55

Cont… : In Single inheritanceClass A{Public :

Void display(){

cout<<“Base class”;}

};

Class B : public A{Public :

Void display(){

cout<<“Derived class”;}

};

Page 56: Inheritance

56

Void main(){B ob;Ob.display();

//ambiguity }

Derived class B has two functions with “display” name – one is its own defined display() and another one is inherited from base class A.

Page 57: Inheritance

57

Cont…In this case, the function of derived class overrides the inherited function.

So, display() of derived class will be executed.

Page 58: Inheritance

58

Cont…If requirement is to execute the display() of base class then: use scope of base class with function name,

like:

Ob.A::display(); // to call base class functionOb.B::display(); // to call derived class

functionOb.display(); // by default calls the derived

class function

Page 59: Inheritance

59

Cont… : In Multiple inheritanceClass A{Public :

Void display(){

cout<<“Base class A”;}

};

Class B {Public :

Void display(){

cout<<“Base class B”;}

};

Page 60: Inheritance

60

Void main(){B ob;Ob.display();

//ambiguity }

Derived class C has three functions with “display” name –

1. its own defined display()2. Display() inherited from base class A.3. Display() inherited from base class B.

Class C : public A, public B{Public :

Void display(){

cout<<“Derived class”;}

};

Page 61: Inheritance

61

Cont…Solution is same as for single inheritance. Use scope of the required class.

Example:Ob.display(); //overrides the display() of A and

B – so default is of class COb.A::display(); //display() of AOb.B::display(); //display() of BOb.C::display(); // display () of C

Page 62: Inheritance

62

Virtual Base classes

Due to the use of more than one inheritance levels, there may be a situation where a child class can have functions of one base class more than once.

For example :A multipath inheritance:

Person

Faculty Student

Performance

Page 63: Inheritance

63

Cont…In the above example, the Performance class inherits both the Faculty and Student class, where these class are inherited from Person class.

If person class contains any method, like displayPerson(), that will be inherited by both Student and Faculty and at last by Performance.

Page 64: Inheritance

64

Cont…At performance, there will be two copies of displayPerson() method. This is the ambiguity.

Solution to this ambiguity is : Virtual base classes.

Page 65: Inheritance

65

Cont…The duplication of inherited members due to these multiple paths can be avoided by making the common base class (ancestor class) as virtual base class while declaring the direct or intermediate base classes.

Page 66: Inheritance

66

Cont… : ExampleClass Person{Public : Void displayPerson()

{ }};

Class Student : virtual public Person{};

Page 67: Inheritance

67

Class Faculty : public virtual Person{};

Class Performance : public Student, public Faculty

{};

Void main(){Performance p;p.displayPerson(); }

Page 68: Inheritance

68

Cont…

In case of virtual base class, C++ takes necessary care to see that only one copy of that class is inherited, regardless of how many inheritance paths exists between the virtual base class and a derived class.

The keywords virtual and accessibility mode (like public) may be used in either order.

Page 69: Inheritance

69

Abstract ClassesAn abstract class is one that is not used to create objects.

It is designed to act as a base class only.

Page 70: Inheritance

70

Constructors in InheritanceIf default constructor is used, firstly compiler searches for a constructor in derived class. If it finds, it uses that; Else it searches in base class and uses the

constructor of base class.

In case of default constructor, if we do not define default constructor in the derived class and there is one defined in the base, the compiler will define one default constructor for us.

Page 71: Inheritance

71

Cont…Note:

As soon as user provides a constructor for a class, C++ will not provide its own one. That’s why the base class sub-object, needs

that base class constructor to be defined by the user.

Page 72: Inheritance

72

Cont…As long as no base class constructor takes any arguments, the derived class need not have a constructor function.

If any base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors.

The argument to the derived constructor will have all the arguments needed for all base classes plus few for itself.

Page 73: Inheritance

73

Cont…If both the derived and base classes contain constructors, the base constructor is executed first and then the constructor in the derived class is executed.

Page 74: Inheritance

74

Cont… : ExampleClass A{Int I;Public :A()

{ i=0; }A (int a)

{ i=a; }};

Class B : public A{Int j;Public :

B() : A() // constructor 1{ j=0; }

B (int x) : A (x) //constructor 2{ j=x; }

B (int x, int y) : A (y) //constructor 3

{ j=x; }};

Page 75: Inheritance

75

Cont…Void main(){

B ob; //calls constructor 1 – initializes i to 0 then j to 0B ob2 (4); //calls constructor 2 – passes 4 to i first then to jB ob3 (5,8) ; //calls constructor 3 – passes 8 to i first then

initializes j with value 5.

}

In case class B does not contain any constructor, the base class constructors will be called but not in the case of parameterized constructors.

Page 76: Inheritance

76

Cont…If we have defined derived class like:

class D: public A, public B, public C { };

the constructor for class A is called first, then constructor for class B and C and then the body of the constructor of class D is executed.

In other words, in case of multiple inheritance, the base classes are constructed in the order in which they appear in the declaration of the derived class.

Page 77: Inheritance

77

Cont…The call to the base class constructors is to be defined outside the body of the constructor, in the member initialization list.

Here this list is called inheritance list.

They cannot be called in the derived class.

Page 78: Inheritance

78

Cont…If one of the classes in the base class list is virtual, then its constructor is called before others.

If there are more such virtual base classes, then their constructors are executed in order of their appearance in the inheritance list.

Page 79: Inheritance

79

Cont…In mulitlevel inheritance, the constructors are executed in the order of inheritance.

For example :In multilevel inheritance, the constructor of first, the

grand base class is executed first, then the constructor of intermediate base class and then the constructor of derived class are executed, that is as per the hierarchy.

Page 80: Inheritance

80

Destructor in inheritance

The destructor of the base classes are called exactly in reverse order of their initialization when the derived object is destroyed.