Inheritance is one of the key features of object-oriented programming, which allows you to create a new class that is a modified version of an existing class. In C++, you can implement inheritance using the class
or struct
keywords, along with the public
, private
, and protected
access specifiers.
Here's an example of how to implement inheritance in C++:
c++#include <iostream>
using namespace std;
// Define a base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Define a derived class that inherits from Shape
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main() {
Rectangle rect;
// Set the width and height of the rectangle
rect.setWidth(5);
rect.setHeight(10);
// Print the area of the rectangle
cout << "Area of the rectangle = " << rect.getArea() << endl;
return 0;
}
In this example, we define a base class Shape
with two protected data members width
and height
, and two public member functions setWidth()
and setHeight()
to set the values of these data members. We then define a derived class Rectangle
that inherits from Shape
using the public
access specifier. The Rectangle
class has one public member function getArea()
that returns the area of the rectangle.
In the main()
function, we create an object rect
of the Rectangle
class and set its width and height using the setWidth()
and setHeight()
member functions inherited from the Shape
class. We then print out the area of the rectangle using the getArea()
member function of the Rectangle
class.
Note that by inheriting from the Shape
class, the Rectangle
class automatically gets access to the width
and height
data members, as well as the setWidth()
and setHeight()
member functions, without having to re-implement them. This allows us to reuse code and avoid duplicating code across different classes.
Comments
Post a Comment