As we know compiler determines the function by the overloaded function signature (like parameter types), but how does this one work:
v[i] = 1;
When compiler looks at these two overloaded functions:
const T& operator[](size_t i) const;
T& operator[](size_t i);
How does it determine which one to use? Does the compiler tries to use 1st one, and finds out it does not work, then it tries to use the second one?
If the object is non-const, the non-const version of the function is invoked (if it is available), else const version is invoked. Now see which is which:
const T& operator[](size_t i) const; //CONST MEMBER FUNCTION
T& operator[](size_t i); //NON-CONST MEMBER FUNCTION
An example,
void f(std::vector<int> const &v1, std::vector<int> & v2)
{
std::cout << v1[0] << std::endl; //invokes const version
std::cout << v2[0] << std::endl; //invokes non-const version
}
Now when you write:
v[i] = 1;
If I don't assume v
to be std::vector
, then it depends on the const-ness of the v
. If v
is const, then const-version will be invoked, else non-const version will be invoked (if it is available, else v
will convert into const object and then const function will be invoked).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments