Passing by reference to a constructor

To assign a reference in a constructor you need to have a reference member

 class A{
     std::string& str;
 public:
     A(std::string& str_)
     :    str(str_) {} 
 };

str is now a reference to the value you passed in. Same applies for const refs

 class A{
     const std::string& str;
 public:
     A(const std::string& str_)
     :    str(str_) {} 
 };

However don’t forget that once a reference has been assigned it can not be changed so if assignment requires a change to str then it will have to be a pointer instead.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)