I have two questions about the following code.
class cls{
int vi;
public:
cls(int v=37) { vi=v; }
friend int& f(cls);
};
int& f(cls c) { return c.vi; }
int main(){
const cls d(15);
f(d)=8;
cout<<f(d);
return 0;
}
- Why does it compile, since f(d) = 8 attemps to modify a const object?
- Why does it still print 15, even after removing the const attribute?
It is not modifying a
constobject as a copy ofdis being made due to the argument off()being passed by value and not by reference. This is also the reason thatdis unchanged as it is not being modified.