---
# System prepended metadata

title: Inheritance example

---

# Inheritance example

```cpp=
#include<stdio.h>

class Rectangle {
    protected:
    int width;
    int height;
    
    public:
    Rectangle(int widthIn, int heightIn) : width(widthIn), height(heightIn) {}
    int area() {
        return width * height;
    }
};

class Square : Rectangle {
    
    // Rectangle 的 protected, public 變數和函式，如width, height, area() 等，
    // 完全繼承到 Square 身上
    
    public:
    // Square 的 constructor 要去呼叫 Rectangle 的 constructor，並提供合適的值
    Square(int length) : Rectangle(length, length) {}
    void print() {
        printf("Square (%d, %d). area is %d.\n", width, height, area());
    }
};

int main() {
    Rectangle r(2, 3);
    Square s(4);
    
    s.print();
    return 0;
}


```