Inheritance in C++
In C++, inheritance is a way for one class to acquire the properties and behaviors of another class. It allows you to create a new class that is a modified version of an existing class. The new class is called a derived class, and the existing class is the base class. The derived class inherits the members of the base class, which means it can use the methods and variables of the base class as if they were its own.
Here is an example of how to use inheritance in C++:
#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);
// Print the area of the object.
std::cout << "Total area: " << rect.getArea() << std::endl;
return 0;
}
In this example, the Rectangle class is derived from the Shape class. The Rectangle class has access to the setWidth and setHeight methods of the Shape class, because they are protected members of the base class. It also has its own method called getArea, which returns the area of the rectangle.
Inheritance is an important concept in object-oriented programming, as it allows you to create relationships between classes and reuse code. It also makes it easier to add new features to your program, because you can modify or extend the behavior of existing classes rather than starting from scratch.
0 Comments