Here is my code:
class NO {
public:
NO(std::string& name):nameValue(name){};
private:
std::string& nameValue; // this is now a reference
};
int main(){
int b=10,c=20;
int& d=b;
d=c;
std::string p="alpha", q="beta";
NO x(p), y(q);
x=y;
return 0;
}
I get the error:
"non-static reference member ‘std::string& NO::nameValue’, can’t use default assignment operator"
Why can't I re-assign the object with a reference member when I can do the same with a built-in type?
thanks
A reference can be initialized, but not assigned to. Once the reference is initialized, it will continue to refer to the same object for as long as it exists. If you don't define an assignment operator, the compiler will synthesize one that does member-wise assignment, but in this case that's impossible, so the compiler can't/won't synthesize one at all.
You can define an assignment operator yourself. It's up to you to decide exactly how to deal with a member that's a reference. Most of the time, you just define your object to not contain any references though.
When you get down to it, the primary use for references is almost certainly as parameters. As members of a class, they don't make sense very often, and in the rare case that they do make sense, the objects of that class probably shouldn't support assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With