Can anyone explain me this error? Here is the code:
class O{
unsigned x;
unsigned y;
public:
O(unsigned x_ ,unsigned y_): x(x_), y(y_){
};
O& operator+= ( O & object){
x += object.x;
}
};
class A {
O item;
public:
A(O i): item(i){;
}
void fun() const{
O j(2,3);
j += item;
}
};
int main(){
return 0;
}
When I try to compile I get this error:
In member function 'void A::fun() const':
[Error] no match for 'operator+=' (operand types are 'O' and 'const O')
[Note] candidate is:
[Note] O& O::operator+=(O&)
[Note] no known conversion for argument 1 from 'const O' to 'O&'
Can anyone explain me this? If I add const qualifier to the argument of the += operator, it compiles. So I think the problem is that I'm passing a reference to item to the += opertor, which is non const, inside the const function fun(). Can anyone explain me why this is illegal, and how I can avoid to do this kind of mistakes, if for instance there is some rule of thumb to follow when using const qualifiers, etc..?