N
Neelesh Bodas
Hello all,
Please consider this code :
class X {
int x;
public:
X(int p ) : x(p) { }
operator int() { x = 1; return x; }
};
X foo(int i)
{
return X(i);
}
int main()
{
int u = 100;
int p = foo(u);
}
What I understand here (Please correct if I am wrong) :
The function foo takes an integer and returns a value of type X (this
is 'return by value'). The return value of foo is stored in some
temporary. This value is then converted to an integer, using operator
int() and then assignment takes place.
What I donot understand is that :
temporaries are always constant. On the other hand, operator int() is
not a const function (rather, it cannot be a const function, it
modifies the data member x). Connsequently, this code should fail to
compile. (How can operator int() be called on a const object ? )
But thats not the case. This is a valid C++ code.
Any explanation will be useful. Thanks.
Please consider this code :
class X {
int x;
public:
X(int p ) : x(p) { }
operator int() { x = 1; return x; }
};
X foo(int i)
{
return X(i);
}
int main()
{
int u = 100;
int p = foo(u);
}
What I understand here (Please correct if I am wrong) :
The function foo takes an integer and returns a value of type X (this
is 'return by value'). The return value of foo is stored in some
temporary. This value is then converted to an integer, using operator
int() and then assignment takes place.
What I donot understand is that :
temporaries are always constant. On the other hand, operator int() is
not a const function (rather, it cannot be a const function, it
modifies the data member x). Connsequently, this code should fail to
compile. (How can operator int() be called on a const object ? )
But thats not the case. This is a valid C++ code.
Any explanation will be useful. Thanks.