SlideShare a Scribd company logo
1 of 80
Inheritance




              1
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
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
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
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
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
Cont…
We can have multiple classes with some
attributes common to them. We would like to
avoid problems of inconsistencies between the
common attributes.




                                           7
Inheritance Syntax
  // Existing class
  class <Base_class>
  {
  };

 // new class
 class <Derived_class> :
 <visibility_mode> <Base_class>
 {
 };

                                  8
Example
// Existing class
                              Inheritance Class
class Base
{
                                  Diagram
};                                Base Class


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


                                               9
Base Class Access Specification

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




                                        10
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
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
Cont…
class child : public Parent
{ };

class Child : protected Parent
{ };

class Child : private Parent
{ };


                                 13
Cont…

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




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




                                              19
Base class


                    Private

                   protected
Derived class       public       Derived class
Protected mode                   Private mode

   Private                          Private

  protected      Derived Class     protected
                  Public mode
    public                           public
                    Private

                   protected

                    public
                                               20
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
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
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
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
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
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
Types of Inheritance

    Single level inheritance
    Multiple level inheritance
    Multilevel inheritance
    Hierarchical inheritance
    Hybrid inheritance



                                 27
Single level inheritance
 It consists of a single base class and a single
 derived class.


               A     Base Class



               B      Derived class



                                                   28
Multiple level inheritance
  It consists of a derived class with more than
  one base class.



        A                   B        Base Class



                  C      Derived class


                                                  29
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
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
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
Hybrid inheritance
 It can be a mixture of any two other levels of
 inheritance.

                            A
          A
                            B
      B        C
                            C         E
          D
                                 F

                                                  33
Some examples of base and derived
classes
An Inheritance hierarchy for university community
members:




                                                    34
A portion of a shape class hierarchy:




                                        35
Accessibility

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




                                          36
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
Cont…: Example 1
Class A              Void main()
{                    {
};                   B ob;
                     Ob.display (); //calls
Class B : public A     function of class B
{                    }
Public :
   void display()
   { }
};
                                          38
Cont…: Example 2
Class A              Void main()
{                    {
Public :             B ob;
   void display()    Ob.display (); //calls
   { }                 function of class A
};                   }

Class B : public A
{
};
                                              39
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
Cont…: Example 3
Class A             Class B : public A
{                   {
Public :            Public :
   void display()      void display()
   { }                 {     }
};                  };




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




                                             42
Cont…

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




                                             43
Cont…: Example 4
Class A             Class B : public A
{                   {
Public :            Public :
   void display()      void display()
   { }                 {     }
};                  };




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




                                            45
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
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
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
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
Cont…
 Faculty class has the accessibility to all the
 methods of Employee and Person classes.

 Accessibility depends upon the visibility of
 base classes.




                                            50
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
Class SportsStudent : public Student, public
  SportsPerson
{
Public:
  void get ()
  {
  getdata();
  getResult();
                                     Void main()
   }
                                     {
  void disp ()
                                       SportsStudent s;
  {
                                       s.getdata();
         display();
                                       s.display ();
         dispResult();
                                     }
  }                                                   52
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
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.




                                             54
Cont… : In Single inheritance
 Class A                    Class B : public A
 {                          {
 Public :                   Public :
    Void display()             Void display()
    {                          {
        cout<<“Base class”;            cout<<“Derived
    }                          class”;
 };                            }
                            };



                                                        55
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
Cont…
 In this case, the function of derived class
 overrides the inherited function.

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




                                               57
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
Cont… : In Multiple inheritance
 Class A                    Class B
 {                          {
 Public :                   Public :
    Void display()             Void display()
    {                          {
        cout<<“Base class             cout<<“Base class
    A”;                        B”;
    }                          }
 };                         };



                                                    59
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
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
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
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
Cont…
 At performance, there will be two copies of
 displayPerson() method. This is the
 ambiguity.

 Solution to this ambiguity is : Virtual base
 classes.




                                          64
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
Cont… : Example
Class Person
{
Public :
Void displayPerson()
   { }
};

Class Student : virtual public Person
{
};

                                        66
Class Faculty : public virtual Person
{
};

Class Performance : public Student, public Faculty
{
};

Void main()
{
Performance p;
p.displayPerson();
}
                                                     67
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
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
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
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
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.

                                                   72
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
Cont… : Example
Class 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
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
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
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.




                                                   77
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
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
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

More Related Content

What's hot

What's hot (20)

Introduction to Inheritance
Introduction to InheritanceIntroduction to Inheritance
Introduction to Inheritance
 
EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
 
Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
inheritance
inheritanceinheritance
inheritance
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Inheritance in c++ part1
Inheritance in c++ part1Inheritance in c++ part1
Inheritance in c++ part1
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
inhertance c++
inhertance c++inhertance c++
inhertance c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in Object Oriented Programming
Inheritance in Object Oriented ProgrammingInheritance in Object Oriented Programming
Inheritance in Object Oriented Programming
 
#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance#OOP_D_ITS - 6th - C++ Oop Inheritance
#OOP_D_ITS - 6th - C++ Oop Inheritance
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 

Viewers also liked

How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in javaTyagi2636
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending ClassesNilesh Dalvi
 
Dynamics allocation
Dynamics allocationDynamics allocation
Dynamics allocationKumar
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 
7. Genetics And Inheritance
7. Genetics And Inheritance7. Genetics And Inheritance
7. Genetics And Inheritancerossbiology
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPTShubham Mondal
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSaharsh Anand
 
Genetics - Mendellian Principles of Heredity
Genetics - Mendellian Principles of HeredityGenetics - Mendellian Principles of Heredity
Genetics - Mendellian Principles of HeredityChristine Joyce Javier
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in PythonSujith Kumar
 
7. Patterns of Inheritance
7. Patterns of Inheritance7. Patterns of Inheritance
7. Patterns of InheritanceMwansa Mulenga
 
Genetics pedigree problems
Genetics pedigree problemsGenetics pedigree problems
Genetics pedigree problemscallr
 
Modes of inheritance-Dr.Gourav
Modes of inheritance-Dr.GouravModes of inheritance-Dr.Gourav
Modes of inheritance-Dr.GouravGourav Thakre
 
Human genetic inheritance patterns
Human genetic inheritance patternsHuman genetic inheritance patterns
Human genetic inheritance patternsRachael Hubbard
 

Viewers also liked (20)

Inheritance
InheritanceInheritance
Inheritance
 
How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in java
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Dynamics allocation
Dynamics allocationDynamics allocation
Dynamics allocation
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Ashish oot
Ashish ootAshish oot
Ashish oot
 
7. Genetics And Inheritance
7. Genetics And Inheritance7. Genetics And Inheritance
7. Genetics And Inheritance
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
01 introduction to oop and java
01 introduction to oop and java01 introduction to oop and java
01 introduction to oop and java
 
Genetics - Mendellian Principles of Heredity
Genetics - Mendellian Principles of HeredityGenetics - Mendellian Principles of Heredity
Genetics - Mendellian Principles of Heredity
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
7. Patterns of Inheritance
7. Patterns of Inheritance7. Patterns of Inheritance
7. Patterns of Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Genetics pedigree problems
Genetics pedigree problemsGenetics pedigree problems
Genetics pedigree problems
 
Modes of inheritance-Dr.Gourav
Modes of inheritance-Dr.GouravModes of inheritance-Dr.Gourav
Modes of inheritance-Dr.Gourav
 
Human genetic inheritance patterns
Human genetic inheritance patternsHuman genetic inheritance patterns
Human genetic inheritance patterns
 

Similar to Inheritance

Inheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ optInheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ optdeepakskb2013
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Shweta Shah
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++RAJ KUMAR
 
MODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerMODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerssuser6f3c8a
 
Inheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridInheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridVGaneshKarthikeyan
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesVinay Kumar
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdfstudy material
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdfWaqarRaj1
 

Similar to Inheritance (20)

Inheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ optInheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ opt
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
inheritence
inheritenceinheritence
inheritence
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Inheritance
Inheritance Inheritance
Inheritance
 
session 24_Inheritance.ppt
session 24_Inheritance.pptsession 24_Inheritance.ppt
session 24_Inheritance.ppt
 
Inheritance
InheritanceInheritance
Inheritance
 
MODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerMODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computer
 
Inheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridInheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybrid
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdf
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
inheritance
inheritanceinheritance
inheritance
 
Set Theory In C++
Set Theory In C++Set Theory In C++
Set Theory In C++
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 

More from ankush_kumar

mathematical induction
mathematical inductionmathematical induction
mathematical inductionankush_kumar
 
mathematical induction
mathematical inductionmathematical induction
mathematical inductionankush_kumar
 
mathematical induction
mathematical inductionmathematical induction
mathematical inductionankush_kumar
 
mathematical induction
mathematical inductionmathematical induction
mathematical inductionankush_kumar
 
Propositional And First-Order Logic
Propositional And First-Order LogicPropositional And First-Order Logic
Propositional And First-Order Logicankush_kumar
 
Soacial networking 3
Soacial networking  3Soacial networking  3
Soacial networking 3ankush_kumar
 
Soacial networking 1
Soacial networking  1Soacial networking  1
Soacial networking 1ankush_kumar
 
Memory organisation
Memory organisationMemory organisation
Memory organisationankush_kumar
 
Social networking 2
Social networking 2Social networking 2
Social networking 2ankush_kumar
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Set theory and relation
Set theory and relationSet theory and relation
Set theory and relationankush_kumar
 

More from ankush_kumar (14)

Social Networking
Social NetworkingSocial Networking
Social Networking
 
mathematical induction
mathematical inductionmathematical induction
mathematical induction
 
mathematical induction
mathematical inductionmathematical induction
mathematical induction
 
mathematical induction
mathematical inductionmathematical induction
mathematical induction
 
mathematical induction
mathematical inductionmathematical induction
mathematical induction
 
Propositional And First-Order Logic
Propositional And First-Order LogicPropositional And First-Order Logic
Propositional And First-Order Logic
 
Oops
OopsOops
Oops
 
Soacial networking 3
Soacial networking  3Soacial networking  3
Soacial networking 3
 
Soacial networking 1
Soacial networking  1Soacial networking  1
Soacial networking 1
 
Memory organisation
Memory organisationMemory organisation
Memory organisation
 
Social networking 2
Social networking 2Social networking 2
Social networking 2
 
Linked list
Linked listLinked list
Linked list
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Set theory and relation
Set theory and relationSet theory and relation
Set theory and relation
 

Inheritance

  • 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. 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. 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. 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. 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. Cont… We can have multiple classes with some attributes common to them. We would like to avoid problems of inconsistencies between the common attributes. 7
  • 8. Inheritance Syntax // Existing class class <Base_class> { }; // new class class <Derived_class> : <visibility_mode> <Base_class> { }; 8
  • 9. Example // Existing class Inheritance Class class Base { Diagram }; Base Class // Derived class class Derived : public Base { Derived Class }; 9
  • 10. Base Class Access Specification It determines how private, protected, and public members of base class can be accessed by derived classes. 10
  • 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. 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. Cont… class child : public Parent { }; class Child : protected Parent { }; class Child : private Parent { }; 13
  • 14. Cont… Note : Private members of base class can never be inherited by derived class. 14
  • 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. 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. 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. 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. 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. 19
  • 20. Base class Private protected Derived class public Derived class Protected mode Private mode Private Private protected Derived Class protected Public mode public public Private protected public 20
  • 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. 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. 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. 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. 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. 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. Types of Inheritance Single level inheritance Multiple level inheritance Multilevel inheritance Hierarchical inheritance Hybrid inheritance 27
  • 28. Single level inheritance It consists of a single base class and a single derived class. A Base Class B Derived class 28
  • 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. 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. 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. 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. 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. Some examples of base and derived classes An Inheritance hierarchy for university community members: 34
  • 35. A portion of a shape class hierarchy: 35
  • 36. Accessibility When objects of derived class access the base class members automatically then it is called accessibility. 36
  • 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. Cont…: Example 1 Class A Void main() { { }; B ob; Ob.display (); //calls Class B : public A function of class B { } Public : void display() { } }; 38
  • 39. Cont…: Example 2 Class A Void main() { { Public : B ob; void display() Ob.display (); //calls { } function of class A }; } Class B : public A { }; 39
  • 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. Cont…: Example 3 Class A Class B : public A { { Public : Public : void display() void display() { } { } }; }; 41
  • 42. Cont… Void main() { B ob; Ob.display(); //calls function of class B } 42
  • 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. Cont…: Example 4 Class A Class B : public A { { Public : Public : void display() void display() { } { } }; }; 44
  • 45. Cont… Void main() { B ob; Ob.display(); //calls function of class B Ob.A::display(); // calls function of A } 45
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 54
  • 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. 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. Cont… In this case, the function of derived class overrides the inherited function. So, display() of derived class will be executed. 57
  • 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. Cont… : In Multiple inheritance Class A Class B { { Public : Public : Void display() Void display() { { cout<<“Base class cout<<“Base class A”; B”; } } }; }; 59
  • 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. 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. 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. 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. 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. 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. Cont… : Example Class Person { Public : Void displayPerson() { } }; Class Student : virtual public Person { }; 66
  • 67. Class Faculty : public virtual Person { }; Class Performance : public Student, public Faculty { }; Void main() { Performance p; p.displayPerson(); } 67
  • 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. 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. 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. 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. 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. 72
  • 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. Cont… : Example Class 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. 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. 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. 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. 77
  • 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. 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. 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

Editor's Notes

  1. See pr11-20.cpp and inheritance.h
  2. See pr11-20.cpp and inheritance.h