Search code examples
c++referencemember-functionsconst-reference

Const reference qualifier on a member function


I have seen in an anwser there: Is returning by rvalue reference more efficient?

The member function definition:

Beta_ab const& getAB() const& { return ab; }

I am familiar with the cv-qualifier (const) on member functions, but not const&.

What does the last const& mean?


Solution

  • The & is a ref-qualifier. Ref-qualifiers are new in C++11 and not yet supported in all compilers, so you don't see them that often currently. It specifies that this function can only be called on lvalues (and not on rvalues):

    #include <iostream>
    
    class kitten
    {
    private:
        int mood = 0;
    
    public:
        void pet() &
        {
            mood += 1;
        }
    };
    
    int main()
    {
        kitten cat{};
        cat.pet(); // ok
    
        kitten{}.pet(); // not ok: cannot pet a temporary kitten
    }
    

    Combined with the cv-qualifier const, it means that you can only call this member function on lvalues, and those may be const.