×

C++ Inheritance


What is inheritance

Inheritance is the most important and useful feature of an Object oriented language. Inheritance is a kind of parent and child relationship or Base Class and Derived Class hierarchy.

Suppose there is a class named as Car. Now we know that every car has the brake system, Gear System, accelerator etc in common. Now think for a while, as a programmer if you have to write the functionality of break, gear system, acceleartor each time for different cars. How painful will it be? So that's why Inheritance came into existence. Inheritance allows you to use a class which includes common features plus you can add your own features into it. This can be done by Derived Class


Syntax :-

class Name : visibilityMode BaseClassName
{
Data members
.........
Member functions
.........
};

visibilityMode indicates the visibility of base class member in derived class. It can be private , public or protected.

Example :-

#include <iostream>
using namespace std;
class Shape {
	public:
		 void area() {
			cout << "Base Class" << endl;
	}
};
class Circle : public Shape {
	public :
	
	void extraFeatureMethod()
	{
		cout<<"Add Extra Fetaure of circle here"<<endl;
	}
};

int main() {
	
Circle c;
c.area();
c.extraFeatureMethod();

return 0;
}

Output :-

Base Class
Add Extra Fetaure of circle here

Circle class is derived class of class Shape with public visibility modifier. Now circle is called as derived class or child class and Shape class is called as super class or parent class. All the member functions in shape class like an area() method is available in derived class. Plus we added one extraFeatureMethod in derived class.