I have written the following code . I worte two functions increase and constincrease which take class references as input . constincrease takes it as constant while increase is simpler and allows it to be modified .
i do not understand why line fails to compile
increase(fun());
// this line fails to compile
.. I know temporary objects are constants and hence the above line can fail as increase takes a non-const reference . However if we see there is another line of code that passes
increase(x3);
Point is why the above line passes but something else fails to compile properly.
class X{
public:
int i ;
};
X fun(){
return X();
}
void increase( X & p )
{
cout<< "\n non-const-increase called ";
p.i++;
}
void constincrease( const X & p )
{
cout<< "\n const-increase called ";
// this function p is const so p.i++; is wrong ...
}
int main(int argc, char *argv[])
{
X x3;
x3.i=9;
increase(x3); // this line passes compilation
constincrease(x3); // const-increase alwasy passes
increase(fun()); // this line fails to compile
constincrease(fun()); // const -increase passes
system("PAUSE");
return EXIT_SUCCESS;
}