How do you overload a member function on const?
Short answer
You can provide both const and non-const overloads of a member function; the compiler picks the const version for const objects and the non-const version for non-const objects.
Advertisement
AModel answer
You can provide both const and non-const overloads of a member function; the compiler picks the const version for const objects and the non-const version for non-const objects. This is common for accessors that return a const reference for const objects and a mutable reference otherwise, avoiding code duplication (or using a const_cast helper).
struct V {
int& at(int i) { return d[i]; }
const int& at(int i) const { return d[i]; }
int d[10];
};Real-world example
A container's operator[] has const and non-const overloads so const containers return read-only references.
Likely follow-ups
- Which overload does a const object call? | How can you avoid duplicating the body?
Related topics