skip to content

Why would a C++ class overload a getter as text() const& and text() &&, and which one does make().text() call?

level: seniorimportance: should knowfreq 35%

answer

  1. the object is an argument too
  2. const picks the const member
  3. temporaries bind to &&
  4. return by value from &&

basics

~20 s

make() returns a temporary, so make().text() calls text() &&, while lvalues use text() const&. The && overload can move the member out and return it by value, so binding its result to a reference no longer dangles.

solid answer

~50 s

A member function has an **implicit object parameter**, and overload resolution ranks it like any other argument. A `const` member function's object parameter is a reference to `const T`, so a non-const object prefers the non-const overload and a const object can only use the const one. **Ref-qualifiers** (C++11) refine this: `text() const&` takes the object as `const Buffer&`, `text() &&` as `Buffer&&`. For the prvalue `make()`, binding an rvalue reference to an rvalue beats binding a const lvalue reference, so `text() &&` is chosen; lvalues cannot bind to `&&` and get `text() const&`. The payoff: the `&&` overload returns `std::string` by value, moving out of an object about to die, so `const std::string& s = make().text();` no longer dangles. One rule: you cannot mix an unqualified overload with ref-qualified ones of the same parameter list.

code

cpp · 21 lines
cpp
#include <cstdio>
#include <string>
#include <utility>

class Buffer {
    std::string data_ = "payload";
public:
    const std::string& text() const& { std::puts("text() const&"); return data_; }
    std::string        text() &&     { std::puts("text() &&");     return std::move(data_); }
};

Buffer make() { return {}; }

int main() {
    Buffer b;
    const Buffer& cb = b;
    std::string a = b.text();        // lvalue: text() const&
    std::string c = cb.text();       // const lvalue: text() const&
    std::string d = make().text();   // prvalue: text() && moves the string out
    std::printf("%s %s %s\n", a.c_str(), c.c_str(), d.c_str());
}

go deeper

for a junior

Know that a member can be overloaded on const, and that a const object can only call const member functions.

for a middle

Explain the implicit object parameter, how const and ref-qualifiers set its type, and which overload lvalues, const lvalues and temporaries select.

for a senior

Show how a && getter returning by value removes a dangling reference into a temporary, and why mixing qualified and unqualified overloads is rejected.

for a principal

Decide when value-type APIs should carry ref-qualified accessors, weighing safety against doubled overload sets, and when C++23 explicit object parameters replace them.

## The object is an argument too For a non-static member function, overload resolution treats the object expression as an extra argument matched against an **implicit object parameter**. Its type depends on how the member is declared: | Declaration | Implicit object parameter | Accepts | |---|---|---| | `void f();` | `X&` (but may also bind rvalues) | non-const lvalues and rvalues | | `void f() const;` | `const X&` | everything | | `void f() &;` | `X&` | non-const lvalues only | | `void f() const&;` | `const X&` | everything | | `void f() &&;` | `X&&` | rvalues only | The ranking rules for **reference bindings** then decide: - Binding to a **less cv-qualified** reference wins: a non-const object prefers `f()` over `f() const`. This is what makes the classic `T& at(i)` / `const T& at(i) const` pair work: `g.at(1) = 5` uses the mutable overload, and inside a function taking `const Grid&` the const one is the only viable choice. - Binding an **rvalue to an rvalue reference** beats binding it to an lvalue reference: a temporary prefers `f() &&` over `f() const&`. ## Why the && overload exists Without it, a getter returning a reference to a member is a lifetime trap on temporaries: ```cpp const std::string& s = make().text(); // only text() const& declared // the Buffer temporary is destroyed at the end of the full-expression; // s now refers to a destroyed member: using it is undefined behaviour ``` Lifetime extension does not help, because it only applies when a reference binds directly to a temporary, not to a reference *returned* from a member of one. Adding `std::string text() &&` changes the picture: 1. `make().text()` now selects the `&&` overload, which moves `data_` out and returns a **prvalue** `std::string`. 2. Binding `const std::string&` to that prvalue extends the returned string's lifetime to that of the reference, so `s` is valid. 3. Lvalues still get the cheap reference from `const&`, with no copy. The code example prints `text() const&` twice and `text() &&` once, matching the table. The standard library uses the same shape: `std::optional::value()` has `&`, `const&`, `&&` and `const&&` overloads, though its rvalue overloads return `T&&`, which still dangles if bound to a named reference; returning by value is the safer choice for your own getters. ## Rules the compiler enforces - **No mixing in one overload set**: two member functions with the same name and parameter list cannot be overloaded if one has a ref-qualifier and the other does not. `void f(); void f() &&;` is rejected; clang says `class member cannot be redeclared`. Once you add `&&`, write `&` or `const&` on the others. - `const` and ref-qualifiers combine freely: `const&`, `&`, `&&` and `const&&` are four distinct object parameters. - C++23's **explicit object parameter** (`deducing this`) can express all four in one template, a technique covered with CRTP and static polymorphism. ## Overloading on a parameter's reference kind The same ranking applies to ordinary parameters. A pair `void set(const std::string&)` and `void set(std::string&&)` sends lvalues to the copying overload and rvalues to the moving one. What does **not** work is pairing by-value with by-reference: `g(int)` and `g(const int&)` are both exact matches for an `int` lvalue, and the call is ambiguous. ## Value categories at the call The overload follows the value category of the object expression, not the variable's declared type: - `b.text()` and `std::as_const(b).text()` are lvalues and take `text() const&`. - `std::move(b).text()` is an xvalue, an rvalue, so it takes `text() &&` and moves `b`'s string out; `b` is left valid but with an unspecified string. - `make().text()` is a prvalue and also takes `text() &&`. ## Where interviewers take it - Expect a request to predict calls on `b`, `std::as_const(b)` and `make()`. - Expect "why return by value from `&&`?": returning `std::string&&` would hand out another reference into the dying object and reintroduce the dangling problem in a subtler form. - Expect the question of cost: the `&&` overload performs one move, which for `std::string` is a few pointer copies.

  • Why can you not declare void text(); and std::string text() &&; in the same class?
    The standard forbids overloading member functions with the same parameter list when some, but not all, carry a ref-qualifier: the unqualified one already accepts both lvalues and rvalues. Clang rejects it with `class member cannot be redeclared`. Qualify every overload, for example `&` and `&&`.
  • Why should text() && return std::string rather than std::string&&?
    Returning `std::string&&` gives the caller a reference into the temporary `Buffer`, which dies at the end of the full-expression, so binding it to a named reference still dangles. Returning by value moves the data into a new object whose lifetime the caller controls.

  • A const member function and a non-const one cannot be overloaded
  • Lifetime extension keeps a member alive when its getter returns a reference
  • An unqualified member can be overloaded with a && version freely
  • Temporaries prefer the const& overload because const binds to anything
  • The && overload should return std::string&& to avoid copying