martixingwei
martixingwei

Reputation: 309

Different results when I define references to same variable in different ways

I defined a class like this

class A
{
public:
    A(int a, int b):a(a),b(b){}
    void test(const char* name) {cout<<name<<": "<<a<<"  "<<b<<endl;}
public:
    int a,b;
};

then the main function:

int main()
{
    A obj(1,2);
    A& ref_1=obj;
    A& ref_2=obj;
    ref_1.a = 2;
    ref_1.test("ref_1");
    ref_2.test("ref_2");
    cout<<&obj<<endl<<&ref_1<<endl<<&ref_2<<endl;
    return 0;
}

the result, as I expect, is

ref_1: 2  2
ref_2: 2  2
0x7fff59bb0c90
0x7fff59bb0c90
0x7fff59bb0c90

However, when I define two references like this:

    A& ref_1=obj, ref_2=obj;

the result is very strange:

ref_1: 2  2
ref_2: 1  2
0x7fff58a68c90
0x7fff58a68c90
0x7fff58a68c80

I use g++ as my compiler. Can anyone tell me why this thing happened?

Upvotes: 1

Views: 75

Answers (3)

kfsone
kfsone

Reputation: 24269

You've fallen afoul of one of precedence.

While what you've written reads as "declare ref_1 and ref_2 as type ref-to-A", the & actually binds to the variable not the type. The same thing happens with pointers. This is why there is some ongoing debate about which is the more correct way to write references/pointers.

A& ref_1; // ref_1 is a reference to type A.
A &ref_1; // means the same thing.

A& ref_1, ref_2;
A &ref_1, ref_2; // same as above.
A &ref_1, &ref_2; // what you thought the first line mean't

A* p1, p2; // p1 is a pointer, p2 is an instance of A
A *p1, *p2; // what you actually intended on the previous line.

Upvotes: 2

PomfCaster
PomfCaster

Reputation: 842

When you write it as A& ref_1=obj, ref_2=obj; it's as if you wrote it as

A& ref_1=obj;
A ref_2=obj;

If you want to write it on one line and have both of them be references you'll need to write it as

A &ref_1=obj, &ref_2=obj;

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119382

A& ref_1=obj, ref_2=obj;

is equivalent to

A& ref_1=obj;
A ref_2=obj;

If you want both to be references, you need to write

A &ref_1=obj, &ref_2=obj;

Alternatively, avoid this confusion altogether, and just write

A& ref_1=obj;
A& ref_2=obj;

like you did originally.

Upvotes: 4

Related Questions