Search code examples
c++getterfunction-qualifierref-qualifier

What is the difference between getters with const, and with const& qualifiers?


I have watched a talk (exact timestamp, not explained by him) by Nicolai Josuttis (member of C++ standard committee) and he stated that ever since C++11, getters should be written like so:

const std::string& getName() const&
{
     return memberStringVar;
} 

The question is, what is the difference comparing to this getter?

const std::string& getName() const
{
     return memberStringVar;
}

Solution

  • In the example given in the talk, there are two overloads of getName() given. One with the && and the other with the const& qualifiers.

    Without the & after the const, the function const std::string& getName() const cannot be overloaded with the overload for rvalues string Customer::getName() &&.

    You would then have to remove the rvalue overload from the code completely if you want it to work.

    Since ref qualified member functions were added only in C++11 (making the getter for rvalues possible), the change from const std::string& getName() const to const std::string& getName() const& was needed to make both overloads possible.

    The C++17 standard draft n4659 states :

    16.1 Overloadable declarations [over.load]
    ...

    2 Certain function declarations cannot be overloaded:
    ...
    (2.3) — Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier.

    Since there is one overload of getName() with a ref-qualifier (&&), the other one also should have the ref qualifier. This is why const& is required.