The following code does not compile:
#include <iostream>
class Foo {
std::string s;
public:
const std::string& GetString() const { return s; }
std::string* GetString() { return &s; }
};
int main(int argc, char** argv){
Foo foo;
const std::string& s = foo.GetString(); // error
return 0;
}
I get the following error:
const1.cc:11: error:
invalid initialization of reference of type 'const std::string&'
from expression of type 'std::string*
It does make some sense because foo
is not of type const Foo
, but just Foo
, so the compiler wants to use the non-const function. But still, why can't it recognize that I want to call the const GetString
function, by looking at the (type of) variable I assign it to? I found this kind of surprising.