Search code examples
c++overloadingaccessorbracketsmutators

Bracket Overload for Assignment and Retrieval; const, reference


Regarding overloading brackets in C++, my compiler is using the mutator method for access. Can anyone tell me why?

1. const int & Cheese::operator [] (int i)const { return weight[i]; } //accessor
2. int & Cheese::operator [] (int i) { return weight[i]; } //mutator

For example, the cout command below is using the mutator function definition--#2 above--to access the data.

Cheese cheddar;
cout << cheddar[2] << endl;

Why is this not using the first function--the accessor--to get the data? I would think that, since the cout is simply a retrieval, it would fire on the first.

How does the compiler know which of these to invoke?

EDIT: For completeness, by mutator, I mean used as a "setter," like so:

cheddar[2] = 100;

Both together would be as follows:

cheddar[2] = cheddar[1];

Where the rhs is just a "getter." It simply retrieves the value of cheddar[1], does not change anything, and thus can be const. In contrast, the lhs bracket overload cheddar[2] functions as a "setter;" the value can be changed, and function return value can't be const.


Solution

  • It invokes the first one for any constant instance (like const Cheese or const Cheese&) and the second one for mutable instances.