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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 thanmy_container.set(3, 9);Of course, you could overload the
[]to do essentially anything, but you probably shouldn’t. You could, for example, causemy_object[3]to incrementmy_objectby 3, but semantically the[]operator conveys lookup-by-index, and it’s always better to have your interfaces conform to expectations.You could use
assertfor 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 thatassertis 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.