S
Samee Zahur
Hi all,
We know that if a function returns by value, assigning to that value
or changing it in any way is meaningless. For example:
int fun();
....
fun()=43; //Definitely an error!!
It is almost (though not quite) as if the return value is a
'const int' rather than a simple 'int' (OK, it's not an l-value).
However, if an object of user-defined type is being returned by
value, none of it's non-const functions are barred from being called.
For example,
class test
{
int a;
public:
test():a(5) {}
void mutate() {a=45;} //mutate() is NOT const
int get() const {return a;}
};
test fun(){return test();}
void main()
{
int i=fun().get(); //Valid, no problem
fun().mutate(); //Why is this valid???
}
Shouldn't only const member functions be allowed on something
that isn't even an l-value?? What if test overloaded the assignment=
operator like this:
test& operator=(int b); //non-const obviously
Would that mean fun()=30; becomes valid above? Why is something like
this allowed?
Samee
P.S. I really do not have a copy of the standard, but I'm assuming
this is right because I trust g++ to be standard-conforming enough.
Please correct me if I am wrong in this case.
We know that if a function returns by value, assigning to that value
or changing it in any way is meaningless. For example:
int fun();
....
fun()=43; //Definitely an error!!
It is almost (though not quite) as if the return value is a
'const int' rather than a simple 'int' (OK, it's not an l-value).
However, if an object of user-defined type is being returned by
value, none of it's non-const functions are barred from being called.
For example,
class test
{
int a;
public:
test():a(5) {}
void mutate() {a=45;} //mutate() is NOT const
int get() const {return a;}
};
test fun(){return test();}
void main()
{
int i=fun().get(); //Valid, no problem
fun().mutate(); //Why is this valid???
}
Shouldn't only const member functions be allowed on something
that isn't even an l-value?? What if test overloaded the assignment=
operator like this:
test& operator=(int b); //non-const obviously
Would that mean fun()=30; becomes valid above? Why is something like
this allowed?
Samee
P.S. I really do not have a copy of the standard, but I'm assuming
this is right because I trust g++ to be standard-conforming enough.
Please correct me if I am wrong in this case.