SlideShare a Scribd company logo
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

PPTX
classes and objects in C++
PPTX
sorting and its types
PPTX
Inheritance in java
PDF
Arrays in Java
PPTX
Types of Constructor in C++
PPTX
Constructor and Types of Constructors
PPTX
Constructors in C++
PPTX
Inheritance in c++
classes and objects in C++
sorting and its types
Inheritance in java
Arrays in Java
Types of Constructor in C++
Constructor and Types of Constructors
Constructors in C++
Inheritance in c++

What's hot (20)

PPTX
Arrays in c
PPTX
Function overloading and overriding
PPTX
Inheritance in JAVA PPT
PPTX
Data types in java
PPT
Operator Overloading
PPTX
Data members and member functions
PPT
C++ Arrays
PPTX
Methods in java
PPT
Final keyword in java
PDF
Strings in java
PPTX
Destructors
PPT
Linked lists
PPTX
Linked List
PPTX
Abstract class in c++
PPTX
INLINE FUNCTION IN C++
PDF
Constructor and Destructor
PPTX
Operator overloading
PPTX
Super Keyword in Java.pptx
PDF
Constructors and destructors
Arrays in c
Function overloading and overriding
Inheritance in JAVA PPT
Data types in java
Operator Overloading
Data members and member functions
C++ Arrays
Methods in java
Final keyword in java
Strings in java
Destructors
Linked lists
Linked List
Abstract class in c++
INLINE FUNCTION IN C++
Constructor and Destructor
Operator overloading
Super Keyword in Java.pptx
Constructors and destructors
Ad

Viewers also liked (20)

PPT
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
PPTX
Inheritance in C++
PPT
Inheritance
PPTX
inheritance c++
PPT
C++ Inheritance
PPTX
Inheritance in c++
PPTX
Inheritance in oops
PPSX
PPTX
Inheritance
PPTX
Conventional memory
PPTX
Department of tourism
PPTX
Dns 2
PPT
Inheritance : Extending Classes
PPTX
File handling functions
PPT
Inheritance
PPTX
Application of greedy method
PPT
C++ Interview Questions
PPTX
Java vs .net
PPSX
PPTX
Spanning trees & applications
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in C++
Inheritance
inheritance c++
C++ Inheritance
Inheritance in c++
Inheritance in oops
Inheritance
Conventional memory
Department of tourism
Dns 2
Inheritance : Extending Classes
File handling functions
Inheritance
Application of greedy method
C++ Interview Questions
Java vs .net
Spanning trees & applications
Ad

Similar to Inheritance (20)

PDF
Chapter 04 inheritance
PPTX
Inheritance
PPTX
Inheritance
PPT
Lecture4
PPT
Lecture4
PPTX
[OOP - Lec 20,21] Inheritance
PDF
lecture-2021inheritance-160705095417.pdf
PPT
Inheritance in C++
PPT
C plus plus Inheritance a complete guide
PPT
Presentation on Polymorphism (SDS).ppt
PPT
C++ polymorphism
PPT
Lecture4
PPTX
Better Understanding OOP using C#
PDF
Inheritance chapter-6-computer-science-with-c++ opt
PPTX
Access controlaspecifier and visibilty modes
PPTX
00ps inheritace using c++
PPTX
03 classes interfaces_principlesofoop
PPT
C++ polymorphism
PPTX
Inheritance
PPTX
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptx
Chapter 04 inheritance
Inheritance
Inheritance
Lecture4
Lecture4
[OOP - Lec 20,21] Inheritance
lecture-2021inheritance-160705095417.pdf
Inheritance in C++
C plus plus Inheritance a complete guide
Presentation on Polymorphism (SDS).ppt
C++ polymorphism
Lecture4
Better Understanding OOP using C#
Inheritance chapter-6-computer-science-with-c++ opt
Access controlaspecifier and visibilty modes
00ps inheritace using c++
03 classes interfaces_principlesofoop
C++ polymorphism
Inheritance
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptx

More from Tech_MX (20)

PPTX
Virtual base class
PPTX
Uid
PPTX
Theory of estimation
PPTX
Templates in C++
PPT
String & its application
PPTX
Statistical quality__control_2
PPTX
Stack data structure
PPT
Stack Data Structure & It's Application
PPTX
Spss
PPTX
Set data structure 2
PPTX
Set data structure
PPTX
Real time Operating System
PPTX
Parsing
PPTX
Mouse interrupts (Assembly Language & C)
PPT
Motherboard of a pc
PPTX
More on Lex
PPTX
MultiMedia dbms
PPTX
Merging files (Data Structure)
PPTX
Memory dbms
PPTX
Linkers
Virtual base class
Uid
Theory of estimation
Templates in C++
String & its application
Statistical quality__control_2
Stack data structure
Stack Data Structure & It's Application
Spss
Set data structure 2
Set data structure
Real time Operating System
Parsing
Mouse interrupts (Assembly Language & C)
Motherboard of a pc
More on Lex
MultiMedia dbms
Merging files (Data Structure)
Memory dbms
Linkers

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Empathic Computing: Creating Shared Understanding
Encapsulation_ Review paper, used for researhc scholars
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Chapter 3 Spatial Domain Image Processing.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
“AI and Expert System Decision Support & Business Intelligence Systems”
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
cuic standard and advanced reporting.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Weekly Chronicles - August'25 Week I
The AUB Centre for AI in Media Proposal.docx
Empathic Computing: Creating Shared Understanding

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.