What’s inheritance in OOP anyway? An example with C++.


class Shape {
double getArea() { return 0.0; }

class Rectangle: public Shape {
double width, height;
Rectangle(double w, double h) {
width = w;
height = h;
double getArea() { return width * height; }

int main() {
Rectangle rect(3, 4);
cout << “Area of rectangle: ” << rect.getArea() << endl;
return 0;


In this example, the class “Shape” is the base class and the class “Rectangle” is the derived class. The class “Rectangle” inherits the method “getArea()” from the class “Shape”, but overrides it to return the area of a rectangle.

When the program runs, it creates an object of the class “Rectangle” and calls the “getArea()” method, which returns the area of the rectangle (12 in this case).

Leave a Reply

Your email address will not be published. Required fields are marked *