0

Let's say you have

class Something
{
    int nVal1;
public:
    Something(int x = 0) { nVal1 = x }
    Something& operator++()
    {
        if (nVal1 == 9)
            nVal1 = 0;
        else
            ++nVal1;

        return *this; 
    }
};

int main()
{
    Something test3;
    ++test3;
}

I am still new to C++ so correct me if I am wrong. The this pointer returns the reference to the object that invokes the overloaded operator++. ++nVal1 is local to the member function, but because it is a member function that operates on the state of the test3 object the value of nVal1 doesn't change unless its reassigned or the object is destroyed? Also, when *this is returned does is it returning the changes to the object? Like here is the

Something object(test3 address) 

with the changes to its state? I understand that Classes allow you to create your own data types and store data. I think the my biggest confusion is what is the function returning and where is it sending it. Does it sort of overwrite the previous state of that object?

sfjac
  • 7,119
  • 5
  • 45
  • 69
Kevin Wiggins
  • 544
  • 5
  • 11

2 Answers2

0

but because it is a member function that operates on the state of the test3 object the value of nVal1 doesn't change unless its reassigned or the object is destroyed?

The value of nVal1 will change when you call operator++() on Something. The fact that you are also returning the new value has nothing to do with the change that you are performing to nVal1.

The semantics of operator++(), on a generic object i, simply requires that you return the new value, so that the behaviour in, for example:

std::cout << (++i);

is defined.

But even if you simply call it and ignore the result, like in your main, the value will still be changed.

Shoe
  • 74,840
  • 36
  • 166
  • 272
0

As written, the code will change test3.nVal1 when operator++() is called - I'm not sure why you think it would not. The returning of *this is a pattern used for some operators to allow chaining; e.g. ++(++test3), or to allow the results of the increment to be, for example, passed to another function, such as being assigned to another Something; e.g.

Something test4 = ++test3;
sfjac
  • 7,119
  • 5
  • 45
  • 69
  • Except that `operator++(int)` should return by value, so in your example: `(test3++)++` would actually increment `test3` only once. And also OP is defining `operator++()` not `operator++(int)`. – Shoe May 25 '15 at 00:08
  • Duh - typing faster than I'm thinking. Fixed. – sfjac May 25 '15 at 00:12