When I compile this code:
class DecoratedString
{
private:
std::string m_String;
public:
// ... constructs, destructors, etc
std::string& ToString() const
{
return m_String;
}
}
I get the following error from g++: invalid initialization of reference of type 'std::string&" from expression of type 'const std::string'.
Why is m_String being treated as const? Shouldn't the compiler simply create a reference here?
EDIT:
Further, what should I do to get this function to act as a conversion to a string that will work in most cases? I made the function const, as it doesn't modify the internal string... maybe I just need to make it return a copy...
EDIT: Okay... making it return a copy worked.
m_String is treated as const because it is accessed as
this->m_String
and this is const because the member function, ToString() is const-qualified.
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