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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> using namespace std; class Fruits { public: Fruits(){ cout<<"Welcome to the fruit world"<<endl; } string Name = "fruits"; }; //This class inherits Teacher class class Apple: public Fruits { public: Apple(){ cout<<"I am Apple"<<endl; } string taste = "Juicy"; string color = "red"; }; int main() { Apple a; cout<<"Color: "<<a.color<<endl; cout<<"Name: "<<a.Name<<endl; cout<<"Taste: "<<a.taste<<endl; return 0; } |
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.