×
>
<

Aptitude

Inheritance in C++

Inheritance in C++

Inheritance in C++ is basically the ability for a class to be able to derive its properties from a different class. It is the most important feature of object oriented programming and allows –

  • High code re-use
  • Lesser time to code
  • Easier to maintain application and edit codes
  • Re-use pre-defined properties and data

Benefits of Inheritance

  • This helps in reduce cost for projects
  • Saves time in coding
  • Decreases complexity of the program
  • Increases reliability

Different Modes of Inheritance in C++

There are three different ways in which we can define relationship between base and derived class while defining inheritance –

1.Public mode:

  1. Public members of base class become public in derived class
  2. Protected members of base class become Protected in derived class
  3. Private members are inaccessible in derived class

2.Protected mode:

  1. Public members of base class become protected in derived class
  2. Protected members of base class become Protected in derived class
  3. Private members are inaccessible in derived class

3.Private mode

  1. Public members of base class become private in derived class
  2. Protected members of base class become private in derived class
  3. Private members are inaccessible in derived class

Syntax for Inheriting Declaration –
  
class NameOfDerivedClass : (Visibility mode) NameOfBaseClass{

// Data Members and functions
}
  

In terms of Parent and Child nomenclature –

Outside the class

  
class NameOfChildClass : (Visibility mode) NameOfParentClass{

// Data Members and functions
}
  
Example
  
class A {

public: 
int x;

protected: 
int y;

private:
int z; 
};

class B : public A { 
 // x stays public
 // y stays protected
 // z is not accessible from B 
};

class C : protected A {
 // x becomes protected
 // y stays protected
 // z is not accessible from C 
};

// 'private' is default for classes
class D : private A { 
 // x becomes private 
 // y becomes private 
 // z is not accessible from D 
};
  
Types of inheritance in C++

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Multiple Inheritance
  4. Hierarchical Inheritance
  5. Hybrid or Multipath Inheritance