Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot generate default assignment operator when a class member is a reference?(in C++)

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

like image 666
user2105632 Avatar asked Sep 04 '14 04:09

user2105632


1 Answers

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.

like image 128
Jerry Coffin Avatar answered Oct 02 '22 01:10

Jerry Coffin