First of all executing of expression a + b results in creating unnamed temporary object. Temporary objects can be binded only with const reference (if of course you are not using the language extensions of MS VC++) .
In the code snip below
1 2 3 4 5 6
|
int main(){
myclass a, b;
myclass c = a + b;
cout << c[1] << endl;
return 0;
}
|
in the statement
myclass c = a + b;
object c is being created. So in this case a copy constructor is used. You did not define a copy constructor yourself so the compiler created implicit copy constructor of type
myclass( const myclass & );
Because this implicit copy constructor has const reference as the parameter it can accept a temporary unnamed object.
Now consider the second code snip
1 2 3 4 5 6 7
|
int main(){
myclass a, b;
myclass c;
c = a + b;
cout << c[1] << endl;
return 0;
}
|
Here object c was created in statement
myclass c;
by using the default constructor. So in statement
c = a + b;
the copy assignment operator will be used instead of the copy constructor. You defined it such a way that it takes non-const reference to an object of the class. But non-const reference can not be binded with a temporary unnamed object. So the compiler issues the error.
Though your copy assignment operator is correct it is better to define it with const reference as the parameter. In this case you can use it with temporary unnamed objects or const objects in the right side of the assignment operator.