Why isn't the compiler smarter in this const function overloading problem?

Posted by Frank on Stack Overflow See other posts from Stack Overflow or by Frank
Published on 2010-04-23T23:57:58Z Indexed on 2010/04/24 0:03 UTC
Read the original article Hit count: 172

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about const