-4

I found an example where in the a class definition, there were 2 member functions defined, but with the same name and same number of arguments:

const MyClass& operator [] (int index) const;
MyClass& operator [] (int index);

My question is how will the compiler know which operator definition it needs to use?

James Hallen
  • 4,534
  • 4
  • 23
  • 28

3 Answers3

1

They are different methods, primarily due to the const suffix.

The return value (alone) cannot be used to resolve overloaded methods or operators.

Edit 1:
You understanding is not correct.

The first function returns a reference, which cannot be modified, to an object. It does not return a copy. The method is not allowed to modify class members.

The second function returns a reference to an object, the object can be modified. The method is allowed to modify class members.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
1

If you attempt to use the operator in a constant function, the constant operator will be called, otherwise, the non-constant one will be called. This is a subtlety that often trips people up as if you only define the non-constant operator but attempt to use it in a constant function it will result in errors.

scohe001
  • 15,110
  • 2
  • 31
  • 51
1

When two methods differ only in the declaration of const, the const version will be selected if it is called from a pointer or reference that is also declared const. Otherwise you will get the non-const version.

This is most commonly seen in the implementation of vector. If you have a const vector, you don't want to be able to change any of the elements, so a const reference to an element is returned.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622