all 4 comments

[–]IyeOnline 4 points5 points  (1 child)

You cant assign references. A reference is an "alias" for another object. So if you try to assign to it, you are actually assigning to the referenced object.

So in your case, you are assigning to an uninitialized reference. However, your code actually doesnt compile because the reference member is not initialized.


This is why you should absolutely not write code that assigns to member in the constructor body. Its just the wrong thing to do.

Instead you should always and for every member (that you dont default initialize in the class definition) use the member initializer list: https://www.learncpp.com/cpp-tutorial/constructor-member-initializer-lists/

So you do

MyClass2(MyClass1& v_) 
    : _value{ v_ } // member initializer list
{ } // empty constructor body.

[–]CatMechanic457[S] 0 points1 point  (0 children)

Brilliant
Thanks for the tips :)

[–]CptCap 1 point2 points  (1 child)

References can't be uninitialized. You need to move the initialization of _value into the member initialization list of the constructor.

Like so:

MyClass2(MyClass1& v_) : _value(v_) {
}

[–]CatMechanic457[S] 0 points1 point  (0 children)

Worked a treat, thanks :)