I'm a bit confused why I was told to return const foo from a binary operator in C ++ instead of just foo.
I read Bruce Eckel's “Thinking in C ++,” and in the chapter on operator overloading, he says that “by making the return value of the [redundant binary operator] const, you declare that only const member function can be called for this return value. This is const-correct because it prevents you from storing potentially valuable information in an object that is likely to be lost. "
However, if I have a plus operator that returns const and a prefix increment operator, this code is not valid:
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 such an assignment, does it not make sense for the + operator to return a value that is not a constant? This can be done by adding const_casts, but it gets rather cumbersome, right?
Thanks!
user220878
source share