Single level Inheritance
Inheritance is a feature in which one class inherits the property of another class. A class which inherits the property is called a derived class or subclass or child class and from which derived class inherits property is called as a base class or parent class. Inheritance makes reusability of code, which avoids rewriting the existing code again and again. A class can be driven from one class or from multiple base classes.
C++ Types of Inheritance
C++ provides different categories of inheritance depending upon the level and ways of properties inherited.- Single inheritance
- Multilevel inheritance
- Multiple inheritance
- Hierarchical inheritance
- Hybrid inheritance
Single Inheritance
Single inheritance is such an inheritance in which a single base class is inherited in only one derived class.C++ Single Inheritance Example
A base class (Polygon) contains properties width, height, and set_values which are inherited in a derived class (Triangle).#include <iostream>
using namespace std;
class Polygon{
protected:
int width,hight;
public:
void set_values (int w,int h){
width=w;
hight=h;
}
};
class Triangle: public Polygon{
public:
int area(){
return ((width*hight)*1/2);
}
};
int main (){
Triangle tri;
tri.set_values (3,4);
cout << "The area of triangle is: " << tri.area() << endl;
return 0;
}
The area of triangle is: 6