example2_bracket_operator.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
#include <iostream>

class Vector {
private:
    int data[2];
public:
    Vector(int x = 0, int y = 0) {
        data[0] = x;
        data[1] = y;
    }

    // Overload the [] operator
    int& operator[](int index) {
        if (index < 0 || index > 1) {
            std::cerr << "Index out of bounds" << std::endl;
            exit(1);
        }
        return data[index];
    }

    // Overload the [] operator for const objects
    const int& operator[](int index) const {
        if (index < 0 || index > 1) {
            std::cerr << "Index out of bounds" << std::endl;
            exit(1);
        }
        return data[index];
    }
};

int main() {
    Vector v(10, 20);
    std::cout << "v[0] = " << v[0] << ", v[1] = " << v[1] << std::endl;

    v[0] = 15;  // Modify the first element
    std::cout << "After modification, v[0] = " << v[0] << std::endl;

    return 0;
}
Back to operator_overloading