temporaries

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.
 
G

Greg

Neelesh said:
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.

The return value may be stored in a temporary. But since foo always
returns the same object, the compiler may optimize the temporary away.
But doing so would not affect the correctness or the outward behavior
of the program.
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 ? )

X's operator() int can be called on a non-const object because it is a
non-const method - which is the only requirement that must be met to
invoke operator int(). There is no rule that states that temporaries
must be constant. True, the compiler will not bind a temporary to a
reference passed as a parameter unless the reference is declared const;
but that rule is not at all the equivalent to a rule that temporaries
themselves must always be const. And in fact there is no such rule.
But thats not the case. This is a valid C++ code.

There is no obvious reason to expect this program not to work.

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top