C++ - Inheritance
Inheritance enables a class to inherit all public and protected properties and methods from another class. The class which is being inherited is called base class or parent class. The class which inherits from another class is called derived class or child class. Inheritance provides re usability of a code and adds more features to a class without modifying it.
Create derived Class
To create a derived class, it is must to specify access specifier and the base class when it is created. See the syntax below. A derived class inherits all public and protected members of base class, and the access specifier defines how these class members of the base class will be inherited in the inherited class.
Syntax
//defining a class class base_class { class members; }; //defining a derived class class derived_class: access_specifier { code statements; };
Example:
In the example below, a base class called Polygon is created which has two data members called length and breadth. Rectangle, a derived class of Polygon is also created using public access specifier. The derived class Rectangle inherits all public and protected members of base class Polygon.
#include <iostream> using namespace std; class Polygon { public: int length = 5; int breadth = 10; }; class Rectangle: public Polygon {}; int main () { Rectangle Rect; cout<<Rect.length<<"\n"; cout<<Rect.breadth<<"\n"; }
The output of the above code will be:
5 10
Access Specifier of Inherited members
The derived class can access all the non-private members of its base class. The base class can be inherited in the derived class through public, private and protected inheritance.
- Public inheritance: access specifier of public members and protected members of the base class will remain same in the derived class.
- Protected inheritance: public members and private members of the base class becomes protected members in the derived class.
- Private inheritance: public members and private members of the base class becomes private members in the derived class.