I m a little confused as to why I ve been told to return const foo from a binary operator in c++ instead of just foo.
I ve been reading Bruce Eckel s "Thinking in C++", and in the chapter on operator overloading, he says that "by making the return value [of an over-loading binary operator] const, you state that only a const member function can be called for that return value. This is const-correct, because it prevents you from storing potentially valuable information in an object that will be most likely be lost".
However, if I have a plus operator that returns const, and a prefix increment operator, this code is invalid:
class Integer{
int i;
public:
Integer(int ii): i(ii){ }
Integer(Integer&);
const Integer operator+();
Integer operator++();
};
int main(){
Integer a(0);
Integer b(1);
Integer c( ++(a + b));
}
To allow this sort of assignment, wouldn t it make sense to have the + operator return a non-const value? This could be done by adding const_casts, but that gets pretty bulky, doesn t it?
Thanks!