Search code examples
c++classoperator-overloadingdereference

Under what condition is the constant dereferencing operator called?


I have a simple class

class Array
{
public:
    Array();
    ~Array();

    // Dereferencing operators
    int operator[](std::size_t index) const;
    int& operator[](std::size_t index);
}

My question is, under what condition is int operator[](std::size_t index) const called? How can I force C++ to call int operator[](std::size_t index) const instead of int& operator[](std::size_t index)? What would happen if I only implement one of the operators?


Solution

  • My question is, under what condition is int operator[](std::size_t index) const called?

    when it's called on an instance of Array that is const

    How can I force C++ to call int operator[](std::size_t index) const instead of int& operator[](std::size_t index)?

    cast the mutable instance of the array to a const reference

    What would happen if I only implement one of the operators?

    If you only implement the const one, you won't be able to write to a subscript using operator[].

    If you only implement the non-const one, you won't be able to read a subscript of a const instance of an Array.