Inheritance: It is relationship between two classes, where we create new class from existing class and inherit the property, existing is Base class and new class is derived class. It’s “is a” relationship.
Example:
- Car is Automobile
- Dog is Animal
Technically: We can create a new class from Base class like “class Dog: public Animal{}“, it tells that Dog class is derived from Animal class and inherit the animal properties. Which are the properties, Dog has been acquired from Animal, it depends upon access specifier, there are three access specifier: public, private and protected.
Data Member or Member function can be public, protected and private, below table explains the accessibility.
Properties | Private | Protected | Public |
Class itself | Yes | Yes | Yes |
Derived class | No | Yes | Yes |
Other class | No | No | Yes |
Base class visibility | Derived class visibility with Private Inheritance | Derived class visibility with Protected Inheritance | Derived class visibility with Public Inheritance |
Private | Cannot be inherited | Cannot be inherited | Cannot be inherited |
Protected | Private | Protected | Protected |
Public | Private | Protected | Public |
Class Diagram:
When will we use inheritance:
When we have a class and it has many functionality that we want, so there is not meaning to write a class from scratch, we can inherit a class from it and re-use its functionality. It will do following :
- We can reuse the existing functionality that has been used and tested.
- We can add new functionality in new class (derived class)
- We can overwrite the base function, if its virtual in Base class.
Note: Inheritance is “is a” relationship so please take care of it. Try to follow Design Principal when you create new class.
source code with example:
Output: