In c++, why does the compiler choose the non-const function when the const would work also?

Two answers spring to mind:

  1. The non-const version is a closer match.

  2. If it called the const overload for the non-const case, then under what circumstances would it ever call the non-const overload?

You can get it to use the other overload by casting a to a const Foo *.

Edit: From C++ Annotations

Earlier, in section 2.5.11 the concept of function overloading was introduced. There it noted that member functions may be overloaded merely by their const attribute. In those cases, the compiler will use the member function matching most closely the const-qualification of the object:


Because a is not a const pointer. Therefore, a non-const function is a closer match. Here is how you can call the const function:

const Foo* b = a;
std::string name = b->Name();

If you have both a const and a non-const overload, and want to call the const one on a non-const object, this might be an indication of bad design.


The compiler does not take into account how you are using the return value in its determination; that's not part of the rules. It doesn't know if you're doing

std::string name = b->Name();

or

b->Name() = "me";

It has to choose the version that works in both cases.