Elegant solution to duplicate, const and non-const, getters? [duplicate]

I recall from one of the Effective C++ books that the way to do it is to implement the non-const version by casting away the const from the other function.

It’s not particularly pretty, but it is safe. Since the member function calling it is non-const, the object itself is non-const, and casting away the const is allowed.

class Foo
{
public:
    const int& get() const
    {
        //non-trivial work
        return foo;
    }

    int& get()
    {
        return const_cast<int&>(const_cast<const Foo*>(this)->get());
    }
};

Leave a Comment