C++ Inheritance

PREV     NEXT

What is inheritance?

  • Inheritance is also one of the most important features of Object Oriented Programming in C++.
  • In inheritance, the child class inherits the properties and functionality of the parent class. When creating a class, instead of writing new data members and member functions we can assign that new class which inherit the members of the existing class and the existing class is known as the base class and the new class is referred as the derived class.

Why and when we should use Inheritance?

  • Let us take a real life example to understand the concept of inheritance there is a group of fruits so, you need to create classes for Apple, Mango, Banana.
  • The methods are taste(), color() which will be same for all of the three classes. If we create these classes avoiding inheritance then we have to write all these functions again and again in each of the three classes which increase the chances of error and data redundancy. So, to avoid this type of situation inheritance is used.
  • If we create a class Fruits and write these two functions in it and inherit the rest of the classes from the fruits class then we can simply avoid the duplication of data and increase re-usability.



Let us have a look at the example:

Advantages of Inheritance

The biggest advantage of using inheritance is the code reusability as we can reuse the members of the parent class so; there is no need to define the member again. So, less code is required in the class.

PREV     NEXT



Share this website !!!
Facebook Twitter Linkedin