Search code examples
c++constantsoverload-resolutionconst-referencefunction-qualifier

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


For example, suppose I have a class:

class Foo
{
public:
    std::string& Name()
    {
        m_maybe_modified = true;
        return m_name;
    }

    const std::string& Name() const
    {
        return m_name;
    }
protected:
    std::string m_name;
    bool m_maybe_modified;
};

And somewhere else in the code, I have something like this:

Foo *a;
// Do stuff...
std::string name = a->Name(); // <-- chooses the non-const version

Does anyone know why the compiler would choose the non-const version in this case?

This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point.


Solution

  • 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: