Published on

  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • See pr11-20.cpp and inheritance.h
  • See pr11-20.cpp and inheritance.h
  • Inheritance

    1. 1. Inheritance 1
    2. 2. Introduction Inheritance 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. 2
    3. 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. 3
    4. 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. 4
    5. 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. 5
    6. 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. 6
    7. 7. Cont…We can have multiple classes with someattributes common to them. We would like toavoid problems of inconsistencies between thecommon attributes. 7
    8. 8. Inheritance Syntax // Existing class class <Base_class> { }; // new class class <Derived_class> : <visibility_mode> <Base_class> { }; 8
    9. 9. Example// Existing class Inheritance Classclass Base{ Diagram}; Base Class// Derived classclass Derived : public Base{ Derived Class}; 9
    10. 10. Base Class Access Specification It determines how private, protected, and public members of base class can be accessed by derived classes. 10
    11. 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 11
    12. 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) 12
    13. 13. Cont…class child : public Parent{ };class Child : protected Parent{ };class Child : private Parent{ }; 13
    14. 14. Cont…Note : Private members of base class can never be inherited by derived class. 14
    15. 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. 15
    16. 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). 16
    17. 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. 17
    18. 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. 18
    19. 19. Cont…The friend functions and the member functionof a class that is a friend of the class can havedirect access to both the private and protecteddata. 19
    20. 20. Base class Private protectedDerived class public Derived classProtected mode Private mode Private Private protected Derived Class protected Public mode public public Private protected public 20
    21. 21. Examples : Private mode Class A Class B : private A { { Private : Private : int i; int a; void fun1() { } void fun4() {} Protected : Protected : int j; int b; void fun2() { } void fun5() { } Public : Public : int k; int c; void fun3() { } void fun6() { } }; }; 21
    22. 22. Cont… Members of class B:  Private members: Member variables : A, j, k Member functions: fun4, fun2, fun3  Protected members: Member variables : b Member functions : fun5  Public members: Member variables : c Member functions : fun6 22
    23. 23. Examples : Protected mode Class A Class B : protected A { { Private : Private : int i; int a; void fun1() { } void fun4() { } Protected : Protected : int j; int b; void fun2() { } void fun5() { } Public : Public : int k; int c; void fun3() { } void fun6() { } }; }; 23
    24. 24. Cont… Members of class B:  Private members: Member variables : A Member functions: fun4  Protected members: Member variables : b, j, k Member functions : fun5, fun2, fun3  Public members: Member variables : c Member functions : fun6 24
    25. 25. Examples : Public mode Class A Class B : public A { { Private : Private : int i; int a; void fun1() { } void fun4() { } Protected : Protected : int j; int b; void fun2() { } void fun5() { } Public : Public : int k; int c; void fun3() { } void fun6() { } }; }; 25
    26. 26. Cont… Members of class B:  Private members: Member variables : a Member functions: fun4  Protected members: Member variables : b, j Member functions : fun5, fun2  Public members: Member variables : c, k Member functions : fun6, fun3 26
    27. 27. Types of Inheritance Single level inheritance Multiple level inheritance Multilevel inheritance Hierarchical inheritance Hybrid inheritance 27
    28. 28. Single level inheritance It consists of a single base class and a single derived class. A Base Class B Derived class 28
    29. 29. Multiple level inheritance It consists of a derived class with more than one base class. A B Base Class C Derived class 29
    30. 30. Multilevel inheritance It consists of derived class of a base class, which behaves as a base class for its another derived class. A Base Class B Derived class of A and Base class of C C Derived class of B 30
    31. 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 31
    32. 32. Hierarchical inheritance It consists of more than one class that are derived from a single base class. A Base Class C B Derived class 32
    33. 33. Hybrid inheritance It can be a mixture of any two other levels of inheritance. A A B B C C E D F 33
    34. 34. Some examples of base and derivedclassesAn Inheritance hierarchy for university communitymembers: 34
    35. 35. A portion of a shape class hierarchy: 35
    36. 36. Accessibility When objects of derived class access the base class members automatically then it is called accessibility. 36
    37. 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. 37
    38. 38. Cont…: Example 1Class A Void main(){ {}; B ob; Ob.display (); //callsClass B : public A function of class B{ }Public : void display() { }}; 38
    39. 39. Cont…: Example 2Class A Void main(){ {Public : B ob; void display() Ob.display (); //calls { } function of class A}; }Class B : public A{}; 39
    40. 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. 40
    41. 41. Cont…: Example 3Class A Class B : public A{ {Public : Public : void display() void display() { } { }}; }; 41
    42. 42. Cont… Void main() { B ob; Ob.display(); //calls function of class B } 42
    43. 43. Cont… To forcefully call the member functions of base class even when already present in derive class, use  Base_class_name :: function_name (); 43
    44. 44. Cont…: Example 4Class A Class B : public A{ {Public : Public : void display() void display() { } { }}; }; 44
    45. 45. Cont…Void main(){B ob;Ob.display(); //calls function of class BOb.A::display(); // calls function of A} 45
    46. 46. Exercise Write 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. 46
    47. 47. Example of Multilevel Inheritance:Class Person Class Employee : public Person{ {Char *name; Int emp_id;Int age; Int salary;Public: Public: void getdata() { } void getemp() { } void display () { } void dispemp () { }}; }; 47
    48. 48. Void main() {Class Faculty : public Faculty f; Employee f.getdata();{ f.getemp();Char *area_of_interest; f.get_Int();Public: void get_Int () { } f.display (); void disp_Int () { } f.dispemp ();}; f.disp_Int(); } 48
    49. 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 49
    50. 50. Cont… Faculty class has the accessibility to all the methods of Employee and Person classes. Accessibility depends upon the visibility of base classes. 50
    51. 51. Example of Multiple Inheritance:Class Student Class SportsPerson{ {Char *name; Char *result;char dob[10]; Public:Public: void getResult () { } void getdata () { } void dispResult () { } void display () { } };}; 51
    52. 52. Class SportsStudent : public Student, public SportsPerson{Public: void get () { getdata(); getResult(); Void main() } { void disp () SportsStudent s; { s.getdata(); display(); s.display (); dispResult(); } } 52
    53. 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. 53
    54. 54. Cont…: Ambiguity resolution inInheritance 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. 54
    55. 55. Cont… : In Single inheritance Class A Class B : public A { { Public : Public : Void display() Void display() { { cout<<“Base class”; cout<<“Derived } class”; }; } }; 55
    56. 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. 56
    57. 57. Cont… In this case, the function of derived class overrides the inherited function. So, display() of derived class will be executed. 57
    58. 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 function Ob.B::display(); // to call derived class function Ob.display(); // by default calls the derived class function 58
    59. 59. Cont… : In Multiple inheritance Class A Class B { { Public : Public : Void display() Void display() { { cout<<“Base class cout<<“Base class A”; B”; } } }; }; 59
    60. 60. Class C : public A, public B Void main(){ {Public : B ob; Void display() Ob.display(); //ambiguity { } cout<<“Derived class”; }}; 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. 60
    61. 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 C Ob.A::display(); //display() of A Ob.B::display(); //display() of B Ob.C::display(); // display () of C 61
    62. 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. Person For example :A multipath inheritance: Faculty Student Performance 62
    63. 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. 63
    64. 64. Cont… At performance, there will be two copies of displayPerson() method. This is the ambiguity. Solution to this ambiguity is : Virtual base classes. 64
    65. 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. 65
    66. 66. Cont… : ExampleClass Person{Public :Void displayPerson() { }};Class Student : virtual public Person{}; 66
    67. 67. Class Faculty : public virtual Person{};Class Performance : public Student, public Faculty{};Void main(){Performance p;p.displayPerson();} 67
    68. 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. 68
    69. 69. Abstract Classes An abstract class is one that is not used to create objects. It is designed to act as a base class only. 69
    70. 70. Constructors in Inheritance If 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. 70
    71. 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. 71
    72. 72. Cont…As long as no base class constructor takes anyarguments, the derived class need not have aconstructor function.If any base class contains a constructor with one ormore arguments, then it is mandatory for the derivedclass to have a constructor and pass the arguments tothe base class constructors.The argument to the derived constructor will have allthe arguments needed for all base classes plus few foritself. 72
    73. 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. 73
    74. 74. Cont… : ExampleClass A Class B : public A{ {Int I; Int j;Public : Public :A() B() : A() // constructor 1 { i=0; } { j=0; }A (int a) B (int x) : A (x) //constructor 2 { i=a; } { j=x; }}; B (int x, int y) : A (y) //constructor 3 { j=x; } }; 74
    75. 75. Cont…Void main(){ B ob; //calls constructor 1 – initializes i to 0 then j to 0 B ob2 (4); //calls constructor 2 – passes 4 to i first then to j B 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. 75
    76. 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. 76
    77. 77. Cont…The call to the base class constructors is to bedefined outside the body of the constructor, inthe member initialization list.  Here this list is called inheritance list.  They cannot be called in the derived class. 77
    78. 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. 78
    79. 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. 79
    80. 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. 80
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.