quote:Original post by foofightrIt''s not the same thing Wildfire posted, but it''s the thing in which Wildfire tried to come up with a counterargument:
civguy, that''s not the same thing.
> Is it valid for a const function to return a reference
> to a member variable and then have the reference edited
> outside of the function?
quote:Your member variable ''int a'' is not const, and you do not modify it inside getA(), so all is well.
This works too:
struct T { T(int& b) : a(b) {} int& a; void setA(int& b) const { a = b; //modified inside }};int main() { int x = 4, y = 8; const T t(x); //note: t is const. cout << t.a << '',''; t.setA(y); cout << t.a;}
Ignore the fact it''s now setA, not getA
quote:Also it doesn''t matter that t is const, because you are not [directly] modifying it, you are using an accessor function.That''s not really the trick in the example, as shown above. I''m not actually modifying ''t''. I''m modifying the memory where t.a points to. At the end of the example, x == y == 8.