Originally Posted by
HelpMeC
What I understood from all this const reference assignment is:
Even if the const version is called in that assignment - the compiler somehow "casts" this const reference to int - to the int value itself (let's call it a copy in practice).
I would discourage understanding it as a cast. Rather, remember that a reference is an alias, i.e., it is another name for what it refers to. Furthermore, if you were to implement a copy assignment operator for a class type, you will find that canonically the parameter is of const reference type.
Originally Posted by
HelpMeC
Of course, in our particular case we can even assign to m1 something because it's non-const object. If it were a const Matrix object - we can't even assign to it anything.
Yes, but remember that that's because the const overload for operator() is designed such that such assignment to change the content of the matrix is impossible.
Originally Posted by
HelpMeC
And he is saying the first one is for when we call the operator[] in case the object is in the left side, and the const version is for when we call this operator in case the object is in the right side.
But you have said that as long as the objects are non-const - the operator which will be called is the non-const one, no matter in which side any one of them.
What's going on here?...
Your instructor is mistaken. You can prove that by writing a program, or changing one of the programs already discussed here to show that for this expression:
Code:
m1(0, 0) = m2(0, 0);
where both m1 and m2 are non-const, the non-const operator() is called twice.
EDIT:
For example, you could compile and run this program:
Code:
#include <iostream>
#include <vector>
class Vector
{
public:
typedef int value_type;
typedef std::size_t size_type;
typedef value_type& reference;
typedef const value_type& const_reference;
explicit Vector(size_type size) : data(size) {}
reference operator[](size_type i)
{
std::cout << "non-const" << std::endl;
return data[i];
}
const_reference operator[](size_type i) const
{
std::cout << "const" << std::endl;
return data[i];
}
private:
std::vector<value_type> data;
};
int main()
{
Vector v1(1);
Vector v2(1);
v1[0] = v2[0];
}