4

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!

4
  • 2
    That code would not compile, which means it does not produce the output you describe. main() is trying to access the private member var of class A, but is not a friend. Commented Jan 8, 2019 at 10:02
  • public: missing in the snippet and it should be a[1] as var is of type std::array Commented Jan 8, 2019 at 10:04
  • 3
    Aside - this is generally considered bad practice because in 6 months when you look at it again, you'll wonder why a[0] doesn't return the first item. Rather than pass around a 1 indexed id; why not make it 0 indexed; and then you don't have to subtract 1 everywhere? Commented Jan 8, 2019 at 10:10
  • 4
    In C++, indexing starts at 0, not 1. Why go against what every C++ programmer knows? Trying to fake 1-based arrays will more than likely lead to very hard-to-find bugs. Commented Jan 8, 2019 at 10:31

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.