Search code examples
c++operator-overloadingincrementlvalue-to-rvalue

How to disallow increment operator when operated multiple times on a object?


How do I overload the increment operator so that this code becomes invalid -

Point p(2, 3);
++++p;

while allowing the following -

Point p(2, 3), a(0, 0), b(1, 4);
a = ++p + b;

Like in C this would be invalid -

int a = 2;
++++a;

Solution

  • One way you could do this is to make your operator++() return a const reference. That would prevent subsequent modification of the returned value, as in a 'chained' ++++p;.

    Here's an outline version that also includes the required binary addition operator, implemented as a non-member function (as is normal):

    #include <iostream>
    
    class Point {
    public:
        int x{ 0 }, y{ 0 };
        Point(int a, int b) : x{ a }, y{ b } {}
        const Point& operator++() { ++x; ++y; return *this; }
        Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; }
    };
    
    inline Point operator+(Point lhs, const Point& rhs)
    {
        lhs += rhs;
        return lhs;
    }
    
    int main()
    {
        Point p(2, 3), a(0, 0), b(1, 4);
        a = ++p + b; // OK: The result of the ++p is passed by value (i.e. a copy)
        std::cout << a.x << " " << a.y << "\n";
    //  ++++a; // error C2678: binary '++': no operator found which takes a left-hand operand of type 'const Point'
        return 0;
    }