1

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?

Henricus V.
  • 898
  • 1
  • 8
  • 29

1 Answers1

1

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.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142