Inheritance - OOPs concept in C++
How is Inheritance used in OOP's concept of C++?
Explanation
Inheritance is a method by which new classes are created or derived from the existing classes. Using Inheritance some qualities of the base classes are added to the newly derived class, apart from its own features The advantage of using "Inheritance" is due to the reusability of classes in multiple derived classes. The ":" operator is used for inherting a class.
The following table lists the visibility of the base class members in the derived classes.
Base class visibility | Derived class visibility |
Public derivation. | Private derivation. | Protected derivation. |
Private | Not inherited | Not inherited | Not inherited |
Protected | Protected | Private | Protected |
Public | Public | Private | Protected |
Following are the different types of inheritance followed in C++.
Example :
#include <iostream.h> class Value { protected: int val; public: void set_values (int a) { val=a;} }; class Square: public Value { public: int square() { return (val*val); } }; int main () { Square sq; sq.set_values (5); cout << "The square of 5 is::" << sq.square() << endl; return 0; } |
Result :
The square of 5 is:: 25
In the above example the object "val" of class "Value" is inherited in the derived class "Square".
Following are the different types of inheritance followed in C++.