example3_constructor_overloading.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
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>

class Rectangle {
private:
    double width;
    double height;

public:
    // Constructor with no parameters
    Rectangle() : width(1.0), height(1.0) {
        std::cout << "Default constructor called" << std::endl;
    }

    // Constructor with one parameter
    explicit Rectangle(double size) : width(size), height(size) {
        std::cout << "Single parameter constructor called" << std::endl;
    }

    // Constructor with two parameters
    Rectangle(double w, double h) : width(w), height(h) {
        std::cout << "Two parameter constructor called" << std::endl;
    }

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

int main() {
    Rectangle rect1;
    Rectangle rect2(5.0);
    Rectangle rect3(3.0, 4.0);

    std::cout << "Area of rect1: " << rect1.area() << std::endl;
    std::cout << "Area of rect2: " << rect2.area() << std::endl;
    std::cout << "Area of rect3: " << rect3.area() << std::endl;

    return 0;
}
Back to constructor