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!
When you say ++x, you’re saying “add 1 to x, store the result back into x, and tell me what it was”. This is the preincrement operator. But, in ++(a+b), how are you supposed to “store the result back into a+b”?
Certainly you could store the result back into the temporary which is presently holding the result of a+b, which would vanish soon enough. But if you didn’t really care where the result was stored, why did you increment it instead of just adding one?