12

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

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

Ever since C++11. The question is, what is the difference comparing to this getter?

const std::string& getName() const
{
     return memberStringVar;
}
Hans Passant
  • 873,011
  • 131
  • 1,552
  • 2,371
Croolman
  • 1,032
  • 10
  • 33

1 Answers1

7

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.

P.W
  • 24,743
  • 6
  • 32
  • 69