T& f() { // some code ... }
const T& f() const { // some code ... }
I\'ve seen this a couple of times now (in the introductory book I\'ve b
As it was mentioned before, you can use const
and non-const
versions of functions depending on the const-ness of the invoking object. The paradigm is very often used with operator[]
for arrays. A way to avoid code duplication (taken from Scott Meyers' book Effective C++) is to const_cast
the const
function return in a non-const overload, such as:
// returns the position of some internal char array in a class Foo
const char& Foo::operator[](std::size_t position) const
{
return arr[position]; // getter
}
// we now define the non-const in terms of the const version
char& Foo::operator[](std::size_t position)
{
return const_cast( // cast back to non-const
static_cast(*this)[position] // calls const overload
); // getter/setter
}