Does overloaded pre-increment operator return the calling object by reference.

Hi everyone :),

I had a small clarification about overloaded pre-increment operator.
I am returning the object by reference in the definition for pre-increment overloading.

Object obj1;
Object obj2 = ++obj1


1) Isn't it true that obj2 refers to obj1 after second line is executed ?

a) If yes, why does changing the value of obj2 doesn't change the value
of obj1 ?

b) If no, does the statement "retrun *this" creates a new object with
same state as object pointed by this pointer and returns that object.

Here is the code :

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
#include <iostream>
#include <memory>

using namespace std;

class Object
{
    public:
        int x;
        Object& operator ++ ()   //Here the calling object is being returned
        {                        // by reference.
            ++x;
            return *this;
        }
};

int main()
{
    Object obj1;

    obj1.x = 20;

    Object obj2 = ++obj1;      //isn't obj2 a reference to obj1 as the
                               //preincrement returns the reference to obj1.
    cout << obj1.x << " " << obj2.x << endl;

    obj2.x = 10;

    cout << obj1.x << " " << obj2.x << endl;

    return 0;
}


output :

21 21
21 10

Thanks for any help here :)
Last edited on
1) Isn't it true that obj2 refers to obj1 after second line is executed ?

It is not true. The variable obj2 is not a reference; references are declared with &.
Object& obj2 = ++obj1;

b) If no, does the statement "return *this" create a new object with
same state as object pointed by this pointer and returns that object.

No: it returns a reference to the current object. A copy is made, but it happens a little bit later, during the initialization of obj2 from the value of the expression ++obj1.
Thanks alot @mbozzi for clarifying this :)
Topic archived. No new replies allowed.