Search code examples
c++operator-overloadingstdarray

Overload operator[] in std::array


I would like to optimize my code overloading the bracket [ ] operator in std::array, which I use everywhere subtracting one. The code compiles but never calls the overloaded function, could anyone tell me why?

#include <iostream>
#include <array>
class A
{
    std::array<int,5> var{0, 1, 2, 3, 4};
    std::array<int, 5ul>::value_type& operator[](std::size_t p_index);
};

std::array<int, 5ul>::value_type& A::operator[](std::size_t p_index)
{
    return var[p_index - 1];
}

int main()
{
    A a;
    std::cout << a.var[1] << std::endl;
}

Code returns "1" but I would expect "0". Thanks in advance!


Solution

  • You are not "overloading" subscription operator [] for your array; you are rather defining your own subscription operator for class A, which will be invoked on instances of A, but not on instances of A's data member var.

    So you need to write...

    std::cout << a[1] << std::endl;
    

    Output:

    0