Overloaded method resolution order

Stuart Brooks stuartb@cat.co.za
Wed Jan 12 12:18:00 GMT 2005


I have a little hassle with overloaded methods which share the same name
except for a const. The class looks like this:

class MyClass
{
public:
  const char* getString() const { return my_string; }

protected:
  char* getString() { return my_string; }

private:
  char* my_string;
};

MyClass c;
char* s1=c.getString();
const char* s2=c.getString();

Both of these cause an error because they resolve to the second getString
and say that it is protected (which it obviously is). The following class
works however :

class MyClass
{
public:
  const char* getString() const { return my_string; }
  char* getString() { return my_string; }
};

According to Stroustrup (7.4), certain criteria are tried in order, so as to
determine which matches the closest. I would have thought that, at least in
the case of s2 (above), the "const char* getString() const" method would
have been selected. I had also hoped that since the second one was
protected, it would use the first one instead in any case. Am I missing
something here?

Regards
 Stuart





More information about the Gcc-help mailing list