Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : automatic const?

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.

like image 431
J. Polfer Avatar asked Jan 22 '26 00:01

J. Polfer


1 Answers

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.

like image 107
James McNellis Avatar answered Jan 24 '26 21:01

James McNellis



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!