example2_member_functions_constructor.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>

struct Rectangle {
    double width;
    double height;

    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const {
        return width * height;
    }

    void scale(double factor) {
        width *= factor;
        height *= factor;
    }
};

int main() {
    Rectangle rect(5.0, 3.0);
    std::cout << "Area: " << rect.area() << std::endl;

    rect.scale(2.0);
    std::cout << "Scaled area: " << rect.area() << std::endl;

    return 0;
}
Back to struct