SlideShare a Scribd company logo
1 of 33
INHERITANCE
Introduction
• Inheritance in C++ is one of the major aspects
  of Object Oriented Programming (OOP). It is
  the process by which one object can inherit or
  acquire the features of another object.
• Inheritance is the process by which new
  classes called derived classes are created from
  existing classes called base classes.
Introduction

• It is a way of creating new class(derived class) from the
  existing class(base class) providing the concept of
  reusability.

• The class being refined is called the superclass or base class
  and each refined version is called a subclass or derived
  class.
• Semantically, inheritance denotes an “is-a” relationship
  between a class and one or more refined version of it.
• Attributes and operations common to a group of subclasses
  are attached to the superclass and shared by each subclass
  providing the mechanism for class level Reusability .
Example


             “Bicycle” is a
           generalization of
           “Mountain Bike”.

          “Mountain Bike” is a
           specialization of
              “Bicycle”.
Defining a Base Class
• Base class has general features common to all the derived
  classes and derived class (apart from having all the features of
  the base class) adds specific features. This enables us to form
  a hierarchy of classes.
                      class Base-class
                       {
                              ... ... ...
                              ………….//Members of base class
                       };
Defining a Derived Class
• The general form of deriving a subclass from a base class is as
  follows

     Class derived-class-name : visibility-mode base-class-name
       {
                 ……………… //
                 ……………….// members of the derived class
       };

• The visibility-mode is optional.
• It may be either private or public or protected, by default it is
  private.
• This visibility mode specifies how the features of base class are
  visible to the derived class.
Example
• Now let’s take the example of ‘computer’ class a bit further by
  actually defining it.
  class computer
  {
       int speed;
       int main_memory;
       int harddisk_memory;
  public:
       void set_speed(int);
       void set_mmemory(int);
       void set_hmemory(int);
       int get_speed();
       int get_mmemory();
        int get_hmemory();
  };
Example
• As you can see, the features (properties and functions) defined in
  the class computer is common to laptops, desktops etc. so we make
  their classes inherit the base class ‘computer’.

  class laptop:public computer
  {
        int battery_time;
       float weight;
  public:
       void set_battime(int);
        void set_weight(float);
       Int get_battime();
       float get_weight();
   };
• This way the class laptop has all the features of the base class
  ‘computer’ and at the same time has its specific features
  (battery_time, weight) which are specific to the ‘laptop’ class.
Example
•   If we didn’t use inheritance we would have to define the laptop class something like this:
           class laptop
           {
                      int speed;
                      int main_memory;
                      int harddisk_memory;
                      int battery_time;
                      float weight;
           public:
                      void set_speed(int);
                      void set_mmemory(int);
                       void set_hmemory(int);
                      int get_speed();
                      int get_mmemory();
                      int get_hmemory();
                      void set_battime(int);
                      void set_weight(float);
                      int get_battime();
                     float get_weight();
            };
•   And then again we would have to do the same thing for desktops and any other class that
    would need to inherit from the base class ‘computer’.
Access Control
  • Access Specifier and their scope
Base Class Access                         Derived Class Access Modes
      Mode        Private                     Public derivation    Protected derivation
                  derivation
Public                   Private              Public               Protected
Private                  Not inherited        Not inherited        Not inherited
Protected                private              Protected            Protected


                                         Access Directly to
         Function Type         Private      Public     Protected       Access
 Class Member                  Yes          Yes        Yes             control to
 Derived Class Member          No           Yes        Yes             class
 Friend                        Yes          Yes        Yes
                                                                       members
 Friend Class Member           Yes          Yes        Yes
Public
• By deriving a class as public, the public
  members of the base class remains public
  members of the derived class and protected
  members remain protected members.
      Class A        Class B        Class B: Public A
     private :        private :       private :
           int a1;       int b1;       int b1;


     protected :      protected :     protected:
        int a2;          int b2;      int a2;
                                      int b2

     public :         public :        public:
        int a3;          int b3;      int b3;int a3;
Example
class Rectangle                                 void Rec_area(void)
    {                                           { area = Enter_l( ) * breadth ; }
    private:                                    // area = length * breadth ; can't be used
    float length ; // This can't be inherited   here
    public:
    float breadth ; // The data and member      void Display(void)
    functions are inheritable                   {
    void Enter_lb(void)                         cout << "n Length = " << Enter_l( ) ;
    {                                            /* Object of the derived class can't
    cout << "n Enter the length of the         inherit the private member of the base
    rectangle : ";                              class. Thus the member
    cin >> length ;                              function is used here to get the value of
    cout << "n Enter the breadth of the        data member 'length'.*/
    rectangle : ";                              cout << "n Breadth = " << breadth ;
    cin >> breadth ;                            cout << "n Area = " << area ;
    }                                           }
    float Enter_l(void)                         }; // End of the derived class definition D
    { return length ; }                         void main(void)
    }; // End of the class definition           {
                                                Rectangle1 r1 ;
   class Rectangle1 : public Rectangle          r1.Enter_lb( );
   {                                            r1.Rec_area( );
   private:                                     r1.Display( );
   float area ;                                 }
   public:
Private
• If we use private access-specifier while deriving a class
  then both the public and protected members of the base
  class are inherited as private members of the derived
  class and hence are only accessible to its members.
      Class A       Class B           Class B : private A

    private :       private :               private :
       int a1;         int b1;              int b1;
                                            int a2,a3;
    protected :     protected :
       int a2;         int b2;              protected:
                                            int b2;
    public :        public :
       int a3;         int b3;              public:
                                            int b3;
Example
class Rectangle                            }
    {                                      };
    int length, breadth;
    public:                                class RecArea : private Rectangle
    void enter()                           {
    {
    cout << "n Enter length: "; cin >>    public:
    length;                                void area_rec()
    cout << "n Enter breadth: "; cin >>   {
    breadth;                               enter();
    }                                      cout << "n Area = " << (getLength() *
    int getLength()                        getBreadth());
    {                                      }
    return length;                         };
    }                                      void main()
    int getBreadth()                       {
    {                                      clrscr();
    return breadth;                        RecArea r ;
    }                                      r.area_rec();
    void display()                         getch();
    {                                      }
    cout << "n Length= " << length;
    cout << "n Breadth= " << breadth;
Protected
• It makes the derived class to inherit the protected
  and public members of the base class as protected
  members of the derived class.
  Class A              Class B          Class B : Protected A

  private :       private :             private :
     int a1;         int b1;               int b1;

  protected :     protected :           protected:
     int a2;         int b2;            int a2;
                                        int b2,a3;

  public :        public :              public:
     int a3;         int b3;            int b3;
Example
class student                     {
{                                 private :
private :                         int a ;
int x;                            void readdata ( );
void getdata ( );                 public :
public:                           int b;
int y;                            void writedata ( );
void putdata ( );                 protected :
protected:                        int c;
int z;                            void checkvalue ( );
void check ( );                   };
};
class marks : protected student
Example
private section
a readdata ( )
public section
b writedata ( )
protected section
c checkvalue ( )
y putdata ( )
z check ( )
Types of Inheritance
• Inheritance are of the following types

             •   Simple or Single Inheritance
             •   Multi level or Varied Inheritance
             •   Multiple Inheritance
             •   Hierarchical Inheritance
             •   Hybrid Inheritance
             •   Virtual Inheritance
Simple Or Single Inheritance
  • Simple Or Single
  Inheritance is a process in
  which a sub class is derived
                                           superclass(base class)
  from only one superclass

  • A class Car is derived from
  the class Vehicle
                                           subclass(derived class)

Defining the simple Inheritance

   class vehicle

             { …..      };
             class car : visibility-mode vehicle
             {
               …………
             };
Example-Payroll System Using Single Inheritance
class emp                                           {
{                                                        cout<<"Enter the basic pay:";
   public:                                               cin>>bp;
    int eno;                                            cout<<"Enter the Humen ResourceAllowance:";
    char name[20],des[20];                               cin>>hra;
    void get()                                           cout<<"Enter the Dearness Allowance :";
    {                                                    cin>>da;
         cout<<"Enter the employee number:";             cout<<"Enter the Profitablity Fund:";
         cin>>eno;                                       cin>>pf;
         cout<<"Enter the employee name:";          }
         cin>>name;                                 void calculate()
         cout<<"Enter the designation:";            {
         cin>>des;                                       np=bp+hra+da-pf;
    }                                               }
};                                                  void display()
                                                    { cout<<eno<<"t"<<name<<"t"<<des<<"t"<<bp<
class salary:public emp                               <"t"<<hra<<"t"<<da<<"t"<<pf<<"t"<<np<<"n
{                                                     ";
   float bp,hra,da,pf,np;                           }
  public:                                      };
   void get1()
Example-Payroll System Using Single Inheritance
void main()                             {s[i].display() }
{                                         getch();      }
    int i,n;                            Output:
    char ch;                            Enter the Number of employee:1
    salary s[10];                       Enter the employee No: 150
    clrscr();                           Enter the employee Name: ram
    cout<<"Enter the number of          Enter the designation: Manager
      employee:";                       Enter the basic pay: 5000
    cin>>n;                             Enter the HR allowance: 1000
    for(i=0;i<n;i++)                    Enter the Dearness allowance: 500
    {                                   Enter the profitability Fund: 300
           s[i].get();
           s[i].get1();                 E.No E.name des BP HRA DA PF
           s[i].calculate();                NP
    }                                   150 ram Manager 5000 1000 500 3
  cout<<"ne_no t e_namet des t bp      00 6200
      thra t da t pf t np n";
   for(i=0;i<n;i++)
Multi level or Varied Inheritance
•   It has been discussed so far that a class can be derived from a class.

•   C++ also provides the facility of multilevel inheritance, according to which the derived class
    can also be derived by an another class, which in turn can further be inherited by another
    and so on called as Multilevel or varied Inheritance.




•   In the above figure, class B represents the base class. The class D1 that is called first level of
    inheritance, inherits the class B. The derived class D1 is further inherited by the class
    D2, which is called second level of inheritance.
Example
class Base                                   cout << "n d1 = " << d1;
     {                                       }
     protected:                              };
     int b;                                  class Derive2 : public Derive1
     public:                                 {
     void EnterData( )                       private:
     {                                       int d2;
     cout << "n Enter the value of b: ";    public:
     cin >> b;                               void EnterData( )
     }                                       {
     void DisplayData( )                     Derive1::EnterData( );
     {                                       cout << "n Enter the value of d2: ";
     cout << "n b = " << b;                 cin >> d2;
     }                                       }
     };                                      void DisplayData( )
     class Derive1 : public Base             {
     {                                       Derive1::DisplayData( );
     protected:                              cout << "n d2 = " << d2;
     int d1;                                 }
     public:                                 };
     void EnterData( )                       int main( )
     {                                       {
     Base:: EnterData( );                    Derive2 objd2;
     cout << "n Enter the value of d1: ";   objd2.EnterData( );
     cin >> d1;                              objd2.DisplayData( );
     }                                       return 0;
     void DisplayData( )                     }
     {
     Base::DisplayData();
Multiple Inheritance
• Deriving a class from more than one direct base class is
  called multiple inheritance.

Defining the Multiple Inheritance
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X :visibilty-mode A, visibilty-mode B, visibilty-mode C
{ /* ... */ };
Example
class Circle // First base class
{
protected:                             cin >> length ;
float radius ;                         cout << “t Enter the breadth : ” ;
public:                                cin >> breadth ;
void Enter_r(void)
{                                      }
cout << "nt Enter the radius: ";     void Display_ar(void)
                                       {
cin >> radius ;                        cout << "t The area = " << (length *
}                                      breadth);
void Display_ca(void)                  }
{                                      };
cout << "t The area = " << (22/7 *    class Cylinder : public Circle, public
radius*radius) ;                       Rectangle
}                                      {
};                                     public:
class Rectangle // Second base class   void volume_cy(void)
{                                      {
protected:                             cout << "t The volume of the cylinder is: "
float length, breadth ;                << (22/7* radius*radius*length) ;
public:                                }
void Enter_lb(void)                    };
{
cout << "t Enter the length : ";
Example
void main(void)
   {
         Circle c ;
         cout << "n Getting the radius of the circlen" ;
         c.Enter_r( );
         c.Display_ca( );
         Rectangle r ;
         cout << "nn Getting the length and breadth of the rectanglenn";
         r.Enter_l( );
         r.Enter_b( );
         r.Display_ar( );
         Cylinder cy ;
         cout << "nn Getting the height and radius of the cylindern";
         cy.Enter_r( );
         cy.Enter_lb( );
         cy.volume_cy( );
   }
Hierarchical Inheritance
• If a number of classes are derived from a single base class, it is
  called as hierarchical inheritance

• Defining the Hierarchical Inheritance
Class student
{…………….};
Class arts: visibility-mode student
{………..…..};
Class science: visibility-mode student
{…………....};
Class commerce: visibility-mode student
{…………….};
Example                                         {
const int len = 20 ;
class student // BASE CLASS                         private:
{                                                   char asub1[len] ;
private: char F_name[len] , L_name[len] ;           char asub2[len] ;
int age, int roll_no ;                              char asub3[len] ;
public:                                             public:
void Enter_data(void)                               void Enter_data(void)
{                                                   { student :: Enter_data( );
cout << "nt Enter the first name: " ; cin >>      cout << "t Enter the subject1 of the arts
F_name ;                                            student: "; cin >> asub1 ;
cout << "t Enter the second name: "; cin >>        cout << "t Enter the subject2 of the arts
L_name ;                                            student: "; cin >> asub2 ;
cout << "t Enter the age: " ; cin >> age ;         cout << "t Enter the subject3 of the arts
cout << "t Enter the roll_no: " ; cin >> roll_no   student: "; cin >> asub3 ;}
;                                                   void Display_data(void)
}                                                   {student :: Display_data( );
void Display_data(void)                             cout << "nt Subject1 of the arts student = "
{                                                   << asub1 ;
cout << "nt First Name = " << F_name ;            cout << "nt Subject2 of the arts student = "
cout << "nt Last Name = " << L_name ;             << asub2 ;
cout << "nt Age = " << age ;                      cout << "nt Subject3 of the arts student = "
cout << "nt Roll Number = " << roll_no ;          << asub3 ;
}};                                                 }};

class arts : public student // FIRST DERIVED
CLASS
Example
class commerce : public student // SECOND
DERIVED CLASS
{
private: char csub1[len], csub2[len], csub3[len] ;
public:
void Enter_data(void)
{                                                    void main(void)
student :: Enter_data( );                            {
cout << "t Enter the subject1 of the commerce       arts a ;
student: ";                                          cout << "n Entering details of the arts studentn" ;
cin >> csub1;                                        a.Enter_data( );
cout << "t Enter the subject2 of the                cout << "n Displaying the details of the arts
commercestudent:";                                   studentn" ;
cin >> csub2 ;                                       a.Display_data( );
cout << "t Enter the subject3 of the commerce       science s ;
student: ";                                          cout << "nn Entering details of the science
cin >> csub3 ;                                       studentn" ;
}                                                    s.Enter_data( );
void Display_data(void)                              cout << "n Displaying the details of the science
{                                                    studentn" ;
student :: Display_data( );                          s.Display_data( );
cout << "nt Subject1 of the commerce student = "   commerce c ;
<< csub1 ;                                           cout << "nn Entering details of the commerce
cout << "nt Subject2 of the commerce student = "   studentn" ;
<< csub2 ;                                           c.Enter_data( );
cout << "nt Subject3 of the commerce student = "   cout << "n Displaying the details of the commerce
<< csub3 ;                                           studentn";
}                                                    c.Display_data( );
};                                                   }
Hybrid Inheritance
• In this type, more than one type of inheritance are used to
  derive a new sub class.
• Multiple and multilevel type of inheritances are used to
  derive a class PG-Student.
class Person
   { ……};                                     Person
class Student : public Person
   { ……};
class Gate Score                             Student      Gate Score
   {…….};
class PG - Student : public Student,       PG - Student
                       public Gate Score
   {………};
Features or Advantages of
                 Inheritance:
Reusability:
•      Inheritance helps the code to be reused in many situations. The
  base class is defined and once it is compiled, it need not be
  reworked. Using the concept of inheritance, the programmer can
  create as many derived classes from the base class as needed while
  adding specific features to each derived class as needed.

Saves Time and Effort:
• The above concept of reusability achieved by inheritance saves the
   programmer time and effort. Since the main code written can be
   reused in various situations as needed

Runtime type inheritance
Exceptions and Inheritance
Overload resolution and inheritance
Disadvantage
Conclusion

• In general, it's a good idea to prefer less
  inheritance. Use inheritance only in the
  specific situations in which it's needed. Large
  inheritance hierarchies in general, and deep
  ones in particular, are confusing to understand
  and therefore difficult to maintain. Inheritance
  is a design-time decision and trades off a lot of
  runtime flexibility.

More Related Content

What's hot

Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
myrajendra
 
Friend functions
Friend functions Friend functions
Friend functions
Megha Singh
 

What's hot (20)

Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Java interface
Java interfaceJava interface
Java interface
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Friend functions
Friend functions Friend functions
Friend functions
 
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
InheritanceInheritance
Inheritance
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 

Viewers also liked

Conventional memory
Conventional memoryConventional memory
Conventional memory
Tech_MX
 
Department of tourism
Department of tourismDepartment of tourism
Department of tourism
Tech_MX
 
File handling functions
File  handling    functionsFile  handling    functions
File handling functions
Tech_MX
 
Application of greedy method
Application  of  greedy methodApplication  of  greedy method
Application of greedy method
Tech_MX
 
Java vs .net
Java vs .netJava vs .net
Java vs .net
Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
Tech_MX
 
Demultiplexer
DemultiplexerDemultiplexer
Demultiplexer
Tech_MX
 
Graph representation
Graph representationGraph representation
Graph representation
Tech_MX
 

Viewers also liked (20)

Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Inheritance
InheritanceInheritance
Inheritance
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Conventional memory
Conventional memoryConventional memory
Conventional memory
 
Department of tourism
Department of tourismDepartment of tourism
Department of tourism
 
Dns 2
Dns 2Dns 2
Dns 2
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
File handling functions
File  handling    functionsFile  handling    functions
File handling functions
 
Inheritance
InheritanceInheritance
Inheritance
 
Application of greedy method
Application  of  greedy methodApplication  of  greedy method
Application of greedy method
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Java vs .net
Java vs .netJava vs .net
Java vs .net
 
Inheritance
InheritanceInheritance
Inheritance
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Demultiplexer
DemultiplexerDemultiplexer
Demultiplexer
 
Graph representation
Graph representationGraph representation
Graph representation
 

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++ opt
deepakskb2013
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
Vinay Kumar
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
FALLEE31188
 

Similar to Inheritance (20)

Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture4
Lecture4Lecture4
Lecture4
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Presentation on Polymorphism (SDS).ppt
Presentation on Polymorphism (SDS).pptPresentation on Polymorphism (SDS).ppt
Presentation on Polymorphism (SDS).ppt
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
Lecture4
Lecture4Lecture4
Lecture4
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
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
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
Inheritance
Inheritance Inheritance
Inheritance
 
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptx
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptxinheriTANCE IN OBJECT ORIENTED PROGRAM.pptx
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptx
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 

More from Tech_MX

Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
Tech_MX
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
String & its application
String & its applicationString & its application
String & its application
Tech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
Tech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure
Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
Tech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
Tech_MX
 
More on Lex
More on LexMore on Lex
More on Lex
Tech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
Tech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
Tech_MX
 

More from Tech_MX (20)

Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Uid
UidUid
Uid
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Spss
SpssSpss
Spss
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Set data structure
Set data structure Set data structure
Set data structure
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
More on Lex
More on LexMore on Lex
More on Lex
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 
Linkers
LinkersLinkers
Linkers
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Inheritance

  • 2. Introduction • Inheritance in C++ is one of the major aspects of Object Oriented Programming (OOP). It is the process by which one object can inherit or acquire the features of another object. • Inheritance is the process by which new classes called derived classes are created from existing classes called base classes.
  • 3. Introduction • It is a way of creating new class(derived class) from the existing class(base class) providing the concept of reusability. • The class being refined is called the superclass or base class and each refined version is called a subclass or derived class. • Semantically, inheritance denotes an “is-a” relationship between a class and one or more refined version of it. • Attributes and operations common to a group of subclasses are attached to the superclass and shared by each subclass providing the mechanism for class level Reusability .
  • 4. Example “Bicycle” is a generalization of “Mountain Bike”. “Mountain Bike” is a specialization of “Bicycle”.
  • 5. Defining a Base Class • Base class has general features common to all the derived classes and derived class (apart from having all the features of the base class) adds specific features. This enables us to form a hierarchy of classes. class Base-class { ... ... ... ………….//Members of base class };
  • 6. Defining a Derived Class • The general form of deriving a subclass from a base class is as follows Class derived-class-name : visibility-mode base-class-name { ……………… // ……………….// members of the derived class }; • The visibility-mode is optional. • It may be either private or public or protected, by default it is private. • This visibility mode specifies how the features of base class are visible to the derived class.
  • 7. Example • Now let’s take the example of ‘computer’ class a bit further by actually defining it. class computer { int speed; int main_memory; int harddisk_memory; public: void set_speed(int); void set_mmemory(int); void set_hmemory(int); int get_speed(); int get_mmemory(); int get_hmemory(); };
  • 8. Example • As you can see, the features (properties and functions) defined in the class computer is common to laptops, desktops etc. so we make their classes inherit the base class ‘computer’. class laptop:public computer { int battery_time; float weight; public: void set_battime(int); void set_weight(float); Int get_battime(); float get_weight(); }; • This way the class laptop has all the features of the base class ‘computer’ and at the same time has its specific features (battery_time, weight) which are specific to the ‘laptop’ class.
  • 9. Example • If we didn’t use inheritance we would have to define the laptop class something like this: class laptop { int speed; int main_memory; int harddisk_memory; int battery_time; float weight; public: void set_speed(int); void set_mmemory(int); void set_hmemory(int); int get_speed(); int get_mmemory(); int get_hmemory(); void set_battime(int); void set_weight(float); int get_battime(); float get_weight(); }; • And then again we would have to do the same thing for desktops and any other class that would need to inherit from the base class ‘computer’.
  • 10. Access Control • Access Specifier and their scope Base Class Access Derived Class Access Modes Mode Private Public derivation Protected derivation derivation Public Private Public Protected Private Not inherited Not inherited Not inherited Protected private Protected Protected Access Directly to Function Type Private Public Protected Access Class Member Yes Yes Yes control to Derived Class Member No Yes Yes class Friend Yes Yes Yes members Friend Class Member Yes Yes Yes
  • 11. Public • By deriving a class as public, the public members of the base class remains public members of the derived class and protected members remain protected members. Class A Class B Class B: Public A private : private : private : int a1; int b1; int b1; protected : protected : protected: int a2; int b2; int a2; int b2 public : public : public: int a3; int b3; int b3;int a3;
  • 12. Example class Rectangle void Rec_area(void) { { area = Enter_l( ) * breadth ; } private: // area = length * breadth ; can't be used float length ; // This can't be inherited here public: float breadth ; // The data and member void Display(void) functions are inheritable { void Enter_lb(void) cout << "n Length = " << Enter_l( ) ; { /* Object of the derived class can't cout << "n Enter the length of the inherit the private member of the base rectangle : "; class. Thus the member cin >> length ; function is used here to get the value of cout << "n Enter the breadth of the data member 'length'.*/ rectangle : "; cout << "n Breadth = " << breadth ; cin >> breadth ; cout << "n Area = " << area ; } } float Enter_l(void) }; // End of the derived class definition D { return length ; } void main(void) }; // End of the class definition { Rectangle1 r1 ; class Rectangle1 : public Rectangle r1.Enter_lb( ); { r1.Rec_area( ); private: r1.Display( ); float area ; } public:
  • 13. Private • If we use private access-specifier while deriving a class then both the public and protected members of the base class are inherited as private members of the derived class and hence are only accessible to its members. Class A Class B Class B : private A private : private : private : int a1; int b1; int b1; int a2,a3; protected : protected : int a2; int b2; protected: int b2; public : public : int a3; int b3; public: int b3;
  • 14. Example class Rectangle } { }; int length, breadth; public: class RecArea : private Rectangle void enter() { { cout << "n Enter length: "; cin >> public: length; void area_rec() cout << "n Enter breadth: "; cin >> { breadth; enter(); } cout << "n Area = " << (getLength() * int getLength() getBreadth()); { } return length; }; } void main() int getBreadth() { { clrscr(); return breadth; RecArea r ; } r.area_rec(); void display() getch(); { } cout << "n Length= " << length; cout << "n Breadth= " << breadth;
  • 15. Protected • It makes the derived class to inherit the protected and public members of the base class as protected members of the derived class. Class A Class B Class B : Protected A private : private : private : int a1; int b1; int b1; protected : protected : protected: int a2; int b2; int a2; int b2,a3; public : public : public: int a3; int b3; int b3;
  • 16. Example class student { { private : private : int a ; int x; void readdata ( ); void getdata ( ); public : public: int b; int y; void writedata ( ); void putdata ( ); protected : protected: int c; int z; void checkvalue ( ); void check ( ); }; }; class marks : protected student
  • 17. Example private section a readdata ( ) public section b writedata ( ) protected section c checkvalue ( ) y putdata ( ) z check ( )
  • 18. Types of Inheritance • Inheritance are of the following types • Simple or Single Inheritance • Multi level or Varied Inheritance • Multiple Inheritance • Hierarchical Inheritance • Hybrid Inheritance • Virtual Inheritance
  • 19. Simple Or Single Inheritance • Simple Or Single Inheritance is a process in which a sub class is derived superclass(base class) from only one superclass • A class Car is derived from the class Vehicle subclass(derived class) Defining the simple Inheritance class vehicle { ….. }; class car : visibility-mode vehicle { ………… };
  • 20. Example-Payroll System Using Single Inheritance class emp { { cout<<"Enter the basic pay:"; public: cin>>bp; int eno; cout<<"Enter the Humen ResourceAllowance:"; char name[20],des[20]; cin>>hra; void get() cout<<"Enter the Dearness Allowance :"; { cin>>da; cout<<"Enter the employee number:"; cout<<"Enter the Profitablity Fund:"; cin>>eno; cin>>pf; cout<<"Enter the employee name:"; } cin>>name; void calculate() cout<<"Enter the designation:"; { cin>>des; np=bp+hra+da-pf; } } }; void display() { cout<<eno<<"t"<<name<<"t"<<des<<"t"<<bp< class salary:public emp <"t"<<hra<<"t"<<da<<"t"<<pf<<"t"<<np<<"n { "; float bp,hra,da,pf,np; } public: }; void get1()
  • 21. Example-Payroll System Using Single Inheritance void main() {s[i].display() } { getch(); } int i,n; Output: char ch; Enter the Number of employee:1 salary s[10]; Enter the employee No: 150 clrscr(); Enter the employee Name: ram cout<<"Enter the number of Enter the designation: Manager employee:"; Enter the basic pay: 5000 cin>>n; Enter the HR allowance: 1000 for(i=0;i<n;i++) Enter the Dearness allowance: 500 { Enter the profitability Fund: 300 s[i].get(); s[i].get1(); E.No E.name des BP HRA DA PF s[i].calculate(); NP } 150 ram Manager 5000 1000 500 3 cout<<"ne_no t e_namet des t bp 00 6200 thra t da t pf t np n"; for(i=0;i<n;i++)
  • 22. Multi level or Varied Inheritance • It has been discussed so far that a class can be derived from a class. • C++ also provides the facility of multilevel inheritance, according to which the derived class can also be derived by an another class, which in turn can further be inherited by another and so on called as Multilevel or varied Inheritance. • In the above figure, class B represents the base class. The class D1 that is called first level of inheritance, inherits the class B. The derived class D1 is further inherited by the class D2, which is called second level of inheritance.
  • 23. Example class Base cout << "n d1 = " << d1; { } protected: }; int b; class Derive2 : public Derive1 public: { void EnterData( ) private: { int d2; cout << "n Enter the value of b: "; public: cin >> b; void EnterData( ) } { void DisplayData( ) Derive1::EnterData( ); { cout << "n Enter the value of d2: "; cout << "n b = " << b; cin >> d2; } } }; void DisplayData( ) class Derive1 : public Base { { Derive1::DisplayData( ); protected: cout << "n d2 = " << d2; int d1; } public: }; void EnterData( ) int main( ) { { Base:: EnterData( ); Derive2 objd2; cout << "n Enter the value of d1: "; objd2.EnterData( ); cin >> d1; objd2.DisplayData( ); } return 0; void DisplayData( ) } { Base::DisplayData();
  • 24. Multiple Inheritance • Deriving a class from more than one direct base class is called multiple inheritance. Defining the Multiple Inheritance class A { /* ... */ }; class B { /* ... */ }; class C { /* ... */ }; class X :visibilty-mode A, visibilty-mode B, visibilty-mode C { /* ... */ };
  • 25. Example class Circle // First base class { protected: cin >> length ; float radius ; cout << “t Enter the breadth : ” ; public: cin >> breadth ; void Enter_r(void) { } cout << "nt Enter the radius: "; void Display_ar(void) { cin >> radius ; cout << "t The area = " << (length * } breadth); void Display_ca(void) } { }; cout << "t The area = " << (22/7 * class Cylinder : public Circle, public radius*radius) ; Rectangle } { }; public: class Rectangle // Second base class void volume_cy(void) { { protected: cout << "t The volume of the cylinder is: " float length, breadth ; << (22/7* radius*radius*length) ; public: } void Enter_lb(void) }; { cout << "t Enter the length : ";
  • 26. Example void main(void) { Circle c ; cout << "n Getting the radius of the circlen" ; c.Enter_r( ); c.Display_ca( ); Rectangle r ; cout << "nn Getting the length and breadth of the rectanglenn"; r.Enter_l( ); r.Enter_b( ); r.Display_ar( ); Cylinder cy ; cout << "nn Getting the height and radius of the cylindern"; cy.Enter_r( ); cy.Enter_lb( ); cy.volume_cy( ); }
  • 27. Hierarchical Inheritance • If a number of classes are derived from a single base class, it is called as hierarchical inheritance • Defining the Hierarchical Inheritance Class student {…………….}; Class arts: visibility-mode student {………..…..}; Class science: visibility-mode student {…………....}; Class commerce: visibility-mode student {…………….};
  • 28. Example { const int len = 20 ; class student // BASE CLASS private: { char asub1[len] ; private: char F_name[len] , L_name[len] ; char asub2[len] ; int age, int roll_no ; char asub3[len] ; public: public: void Enter_data(void) void Enter_data(void) { { student :: Enter_data( ); cout << "nt Enter the first name: " ; cin >> cout << "t Enter the subject1 of the arts F_name ; student: "; cin >> asub1 ; cout << "t Enter the second name: "; cin >> cout << "t Enter the subject2 of the arts L_name ; student: "; cin >> asub2 ; cout << "t Enter the age: " ; cin >> age ; cout << "t Enter the subject3 of the arts cout << "t Enter the roll_no: " ; cin >> roll_no student: "; cin >> asub3 ;} ; void Display_data(void) } {student :: Display_data( ); void Display_data(void) cout << "nt Subject1 of the arts student = " { << asub1 ; cout << "nt First Name = " << F_name ; cout << "nt Subject2 of the arts student = " cout << "nt Last Name = " << L_name ; << asub2 ; cout << "nt Age = " << age ; cout << "nt Subject3 of the arts student = " cout << "nt Roll Number = " << roll_no ; << asub3 ; }}; }}; class arts : public student // FIRST DERIVED CLASS
  • 29. Example class commerce : public student // SECOND DERIVED CLASS { private: char csub1[len], csub2[len], csub3[len] ; public: void Enter_data(void) { void main(void) student :: Enter_data( ); { cout << "t Enter the subject1 of the commerce arts a ; student: "; cout << "n Entering details of the arts studentn" ; cin >> csub1; a.Enter_data( ); cout << "t Enter the subject2 of the cout << "n Displaying the details of the arts commercestudent:"; studentn" ; cin >> csub2 ; a.Display_data( ); cout << "t Enter the subject3 of the commerce science s ; student: "; cout << "nn Entering details of the science cin >> csub3 ; studentn" ; } s.Enter_data( ); void Display_data(void) cout << "n Displaying the details of the science { studentn" ; student :: Display_data( ); s.Display_data( ); cout << "nt Subject1 of the commerce student = " commerce c ; << csub1 ; cout << "nn Entering details of the commerce cout << "nt Subject2 of the commerce student = " studentn" ; << csub2 ; c.Enter_data( ); cout << "nt Subject3 of the commerce student = " cout << "n Displaying the details of the commerce << csub3 ; studentn"; } c.Display_data( ); }; }
  • 30. Hybrid Inheritance • In this type, more than one type of inheritance are used to derive a new sub class. • Multiple and multilevel type of inheritances are used to derive a class PG-Student. class Person { ……}; Person class Student : public Person { ……}; class Gate Score Student Gate Score {…….}; class PG - Student : public Student, PG - Student public Gate Score {………};
  • 31. Features or Advantages of Inheritance: Reusability: • Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed. Saves Time and Effort: • The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed Runtime type inheritance Exceptions and Inheritance Overload resolution and inheritance
  • 33. Conclusion • In general, it's a good idea to prefer less inheritance. Use inheritance only in the specific situations in which it's needed. Large inheritance hierarchies in general, and deep ones in particular, are confusing to understand and therefore difficult to maintain. Inheritance is a design-time decision and trades off a lot of runtime flexibility.