I have a class with a string attribute, and my getters have to return string& values for those attributes.
The only way I managed to do it without getting errors is like this :
inline string& Class::getStringAttribute() const{
static string dup = stringAttribute;
return dup;
}
What is the correct way to write a getter returning a string reference of a private string attribute in C++ ?
Doing it like this :
inline string& Class::getStringAttribute() const{
return stringAttribute;
}
Gets me this error :
error: invalid initialization of reference of type ‘std::string& {aka std::basic_string<char>&}’ from expression of type ‘const string {aka const std::basic_string<char>}’
Either return a copy or a const reference:
std::string get() const { return s_; }
const std::string& get() const { return s_; }
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