views:

116

answers:

4

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.

+8  A: 

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.

James McNellis
+1  A: 

Because the method is const (the const in std::string& ToString() const). Const method see this as a const object, and its memebers as const objects, too.

jpalecek
+1  A: 

Because you access m_String through a constant this (the method is const).

doublep
+3  A: 

m_String is const at that point because you've chosen to declare the method as const (which of course makes all data instance members const, too) -- if you need to bypass that for that specific data member, you could choose to explicitly make it mutable.

Alex Martelli