Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to return string reference in getter

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>}’
like image 496
Jean-Pierre Coffe Avatar asked Aug 10 '26 18:08

Jean-Pierre Coffe


1 Answers

Either return a copy or a const reference:

std::string get() const         { return s_; }
const std::string& get() const  { return s_; }
like image 72
edwinc Avatar answered Aug 13 '26 00:08

edwinc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!