Difference between a const and non-const function in C++

Since you're declaring a mutable Array instance, the first function is used.

You need a const instance in order for the second one to be used:

const Array myArray;

// As this is const, only the second function can work
cout << myArray[2];

If you read the function signatures carefully, the second one has const at the end which means it applies to const instances. Normally if no non-const version is defined, this is the one that will run, but as you've gone out of your way to make the other version, that's the one that's called.

The first function allows mutation because it returns a reference instead of a copy:

myArray[2] = 5;

Where that actually changes the array. The const version does not permit this, you get a temporary value instead.

Tags:

C++