I have been reading a C++ book and found these two functions:
int &Array::operator []( int subscript ) // first
{
//code
return ptr[ subscript ];
}
int Array::operator[]( int subscript ) const //second
{
//code
return ptr[ subscript ]; // value return
}
The idea is to create an Array object and access some private members, for example:
Array myArray;
cout << myArray[ 2 ];
But I don't get the difference between those functions, basically because every time I type something like "cout << myArray[ 2 ]" the first function is called. So , when is the second function called? Does the second function work?
It is a fixed variable that cannot be changed after defining the variable in a program. The value of a variable can change depending on the conditions. In constants, the value cannot be changed. Typically, it uses int, float, char, string, double, etc.
Constant Functions means that they will remain same throughout the execution of the program. Non-constant variable are those whose value can be changed at any point during the execution of the program. Therefore, Non constant variables can't be used because they change the behaviour of the function.
Const member functions in C++ It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.
const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With