Search code examples
c++operator-overloadingsubscript-operator

Overloading of operator[]


What are the scenarios which may need to overload the subscript operator?

And what has the assert function got to do with this? I see in most cases of subscript overloading use of assert, would need an explanation on that.


Solution

  • You might overload the [] operator on a custom container, to provide a syntactically/semantically clearer way of accessing elements.

    For example my_container[3] = 9; is somewhat clearer than my_container.set(3, 9);

    Of course, you could overload the [] to do essentially anything, but you probably shouldn't. You could, for example, cause my_object[3] to increment my_object by 3, but semantically the [] operator conveys lookup-by-index, and it's always better to have your interfaces conform to expectations.

    You could use assert for quick-and-dirty bounds checking; it will cause your program to die messily, which is always preferable to introducing subtle memory corruption. The benefit is that assert is a macro which can be compiled out of production code, meaning you may pay the overhead of bounds-checking your container in development and not in production with no modification to your code.