Inheritance
Lesson 31Author : Afrixi
Last Updated : November, 2022
Inheritance is a key concept in object-oriented programming that allows a class to inherit properties and behaviors from another class, known as the base or parent class. The class that inherits these properties and behaviors is called the derived or child class.
In C++, inheritance is implemented using the class keyword followed by the name of the derived class and the base class that it is inheriting from, separated by a colon. Here’s an example:
#include <iostream>
// base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(7);
std::cout << "Area of rectangle: " << rect.getArea() << std::endl;
return 0;
}
In this example, we define a Shape
base class with two protected data members width
and height
and two public member functions setWidth
and setHeight
for setting these data members. We then define a Rectangle
derived class that inherits from the Shape
base class using the public
keyword.
The Rectangle
class has a single member function getArea
that calculates the area of the rectangle using the width
and height
data members inherited from the Shape
base class.
In the main function, we create an object rect
of the Rectangle class and call the setWidth
and setHeight
member functions to set the width
and height
of the rectangle. We then call the getArea
member function to calculate and print the area of the rectangle.
Inheritance allows us to reuse code and avoid duplicating similar functionality across different classes. It also enables us to create more complex class hierarchies and models for our programs.