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 (20)

Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
class and objects
class and objectsclass and objects
class and objects
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
stack & queue
stack & queuestack & queue
stack & queue
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
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 in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Dfs presentation
Dfs presentationDfs presentation
Dfs presentation
 
Inheritance
InheritanceInheritance
Inheritance
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 

Viewers also liked

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...cprogrammings
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Laxman Puri
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oopsHirra Sultan
 
Conventional memory
Conventional memoryConventional memory
Conventional memoryTech_MX
 
Department of tourism
Department of tourismDepartment of tourism
Department of tourismTech_MX
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending ClassesNilesh Dalvi
 
File handling functions
File  handling    functionsFile  handling    functions
File handling functionsTech_MX
 
Application of greedy method
Application  of  greedy methodApplication  of  greedy method
Application of greedy methodTech_MX
 
Java vs .net
Java vs .netJava vs .net
Java vs .netTech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Demultiplexer
DemultiplexerDemultiplexer
DemultiplexerTech_MX
 
Graph representation
Graph representationGraph representation
Graph representationTech_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 oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
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

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
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
 
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
 
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
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objects
 

More from Tech_MX

Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimationTech_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 applicationTech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_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 2Tech_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 SystemTech_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 pcTech_MX
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbmsTech_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 dbmsTech_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

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

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.