2

I got an assignment to implement a template array class. One of the requirement is to overload the [] operator. I made this two const and non-const version which seems to be working fine.

const T& operator[](const unsigned int index)const

and

T& operator[](const unsigned int index)

My question is how will the compiler know which one to run when i will do something like:

int i=arr[1]

On a non-const array?

Ravid Goldenberg
  • 2,119
  • 4
  • 39
  • 59

2 Answers2

10

The non-const function will always be called on a non-const array, and the const function on a const array.

When you have two methods with the same name, the compiler selects the best-fitting one based on the type of the arguments, and the type of the implicit object parameter (arr).

I just answered a similar question the other day, you may find it helpful: https://stackoverflow.com/a/16922652/2387403

Community
  • 1
  • 1
Taylor Brandstetter
  • 3,523
  • 15
  • 24
2

It all depends on your declaration of the object. If you have

const T arr[];
...
int i=arr[1];

Then the const version will be called, but if you have

T arr[];
...
int i=arr[1];

Then the non-const version will be called. So in the example you gave, since it was a non-const array, the non-const version will be called.

David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
  • Do you mean that the compiler will simply prefer to call the non-const version over the const one? If so can you please explain why? – Ravid Goldenberg Jun 05 '13 at 19:58
  • @petric Yes, it will. As for why, imagine what would happen if every time you called a function it would default to the const version. It would be impossible to do anything, and moreover there would be no point in having a non-const version of the function because it would never be called. – David says Reinstate Monica Jun 05 '13 at 20:01