Inheritance in C++

Inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class. ... The derived class is the specialized class for the base class.

Purpose of Inheritance

  • ·        Code Reusability
  • ·        Method Overriding (Hence, Runtime Polymorphism.)
  • ·        Use of Virtual Keyword Basic

Syntax of Inheritance:

Subclass_name : access_specifier Superclass_name

{

       //body of subclass

};

 

 

Example: Inheritance

Class Aminal{

     int leg=3;

Public:

     void display(){

      cout<<”The legs is = ”<<legs;

     }

};

class dog: public Animal   //inheritance

 


There are six types of inheritance:

·        Single Inheritance
·        Multi Level Inheritance
·        Multiple Inheritance
·        Hierarchical Inheritance
·        Hybrid Inheritance


 Important Points of Inheritance

 Modes of Inheritance:

1.   Public mode: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class.

2.   Protected mode: If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class.

3.   Private mode: If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class. 

 

Important Note : The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed. For example, Classes B, C and D all contain the variables x, y and z in below example. It is just question of access



Post a Comment

0 Comments

Close Menu