no one special
no one special

Reputation: 1756

Providing const and non-const version of functions

Maybe it is a trivial question, but I can't actually find an answer. If I have a class like in the example below do I need to provide both const and non-const version of functions like in case of std::vector? Would a single constexpr function do the same job?

template <typename Type>
class Collection
{
    public:

        virtual ~Collection() {}

        virtual size_t size() noexcept = 0;
        virtual size_t size() const noexcept = 0;
        virtual Type operator[](size_t index) noexcept = 0;
        virtual Type operator[](size_t index) const noexcept = 0;
};

Upvotes: 1

Views: 132

Answers (1)

Dean Johnson
Dean Johnson

Reputation: 1852

It depends. If the non-const version would do the same thing as the const version, then no. If someone has a non-const instance of a class, they can still call const methods.

There are some methods that may need both. Consider your indexing operator. If it instead returned a reference to the type, you would probably want both:

virtual Type& operator[](size_t index) noexcept = 0;
virtual const Type& operator[](size_t index) const noexcept = 0;

The methods aren't exactly the same because they are returning different types. This would mean that if someone has a const instance of your type, they could not get a mutable reference to an element.

A single constexpr function could do the job as long as the potential const/non-const implementations would be the same.

Upvotes: 3

Related Questions