Ian McGrath
Ian McGrath

Reputation: 1012

Post increment operator for user defined types's behavior

I was going through some book and I decided to write my own implementation of post-increment operator for user defined type. Here is the code.

#include <iostream>

using namespace std;

class X
{
    int a;

    public:
    X(int x=1):a(x){}

    X operator++(int)
    {
        X oldobj = *this;
        (*this).a++;
        return oldobj;
    }

int get(){return a;}

};

int main()
{
    X obj,obj2;
    obj++ = obj2;
    cout<< obj.get() << endl;
    return 0;
}   

I would expect the output to be 1 since obj2's value will be copied after the increment is done. But the output was 2.

Thoughts?

P.S. I know this code will not win any medals and its fallacies. It is just for my understanding. Incidentally, ++obj = obj2 returns 1;

Is the behavior undefined?

Upvotes: 2

Views: 1611

Answers (3)

Luchian Grigore
Luchian Grigore

Reputation: 258618

As your syntax tells you, the postfix operator returns a copy of the old value, so that's what gets incremented, not your object.

Basically,

obj++ = obj2;

Will do this:

X tempObj = obj;
obj ++;
tempObj = obj2;

You're assigning obj2 to a temporary variable.

Upvotes: 5

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

obj++ returns a temporary object holding the old value.

So, although "obj2's value will be copied after the increment is done" is true, it's not copied into the original obj at all :)

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254661

The behaviour is actually well-defined.

You are assigning to the result of obj++, which is a temporary - a copy of obj from before the post-increment. This assignment does not affect obj, which retains its value of 2 from the increment.

The code is roughly equivalent to:

X temp = obj;
obj++;
temp = obj2;

Upvotes: 1

Related Questions