Object that is passed by reference isn't updated from original reference

Here is the code that confuses me
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
33
#include <iostream>

class A {
   int value=10;
public:
    void setValue(int value) {
        A::value = value;
    }

    int getValue() const {
        return value;
    }
};

class B {
    A a;
public:
    B(A &a) : a(a) {}

    const A &getA() const {
        return a;
    }
};

int main() {
    A a;
    B b(a);

    a.setValue(15);
    std::cout << b.getA().getValue();
    
    return 0;
}



I pass "a" to B constructor by reference. I expected that b.getA().getValue() will return 15, it returns 10.

What am I missing?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class B {
    
    // A a; // this is a data member of the class
            // this holds a value of type A (it is a copy local to the object of type B)
            // ie. an object of type B contains a sub-object of type A   
    
    A& a; // this is a reference member of the class
          // this holds an alias (a reference) to the object of type A (constructor arg)
public:
    B(A &a) : a(a) {}

    const A &getA() const {
        return a;
    }
};
So what does this constructor do?

B(A &a) : a(a) {}

I thought it passes the value of "a" by reference, who creates another instance of A?
> So what does this constructor do? B(A &a) : a(a) {}

If a is a data member of the class, it copy initialises the data member.
(B::a becomes a copy of the object referred to by the constructor argument)

If a is a reference member of the class, it initialises the reference member.
(B::a refers to the same object that is referred to by the constructor argument)
This is interesting - thank you.
Thank you for this informative discussion @afedorov and @JLBorges.
Registered users can post here. Sign in or register to post.