2023-01-21

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

###

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

class Rectangle: public Shape {
private:
double width, height;
public:
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).

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *