Discussion:
C-type casting
(too old to reply)
Vladimir Grigoriev
2009-12-16 14:58:05 UTC
Permalink
As I remember the following quetstion about C-type casting was already
asked. I.e.

the expression

int i;

( int )i = 10;

is invalid.

My question is relative to classes. Which type of object is generated? I.e.
with const or without const specifier?

T obj1, obj2;

( T )obj1 = obj2;

Vladimir Grigoriev
Igor Tandetnik
2009-12-16 16:26:04 UTC
Permalink
Post by Vladimir Grigoriev
My question is relative to classes. Which type of object is
generated? I.e. with const or without const specifier?
T obj1, obj2;
( T )obj1 = obj2;
The call is equivalent to

T(obj1).operator=(obj2);

where T(obj1) produces a temporary. Temporaries are strange beasts in C++, not quite lvalues and not quite rvalues. It's legal to call a non-const method on a temporary, but illegal to bind it to a non-const reference. Which leads to perennial questions like this:

string out;

int n;
ostringstream(out) << n; // compiles

string str;
ostringstream(out) << str; // doesn't compile

I'll leave it as an exercise for the reader to figure out why the code behaves the way it does (to reproduce this problem with VC, set Project | Properties | C/C++ | Language | Disable Language Extensions = Yes).
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead. -- RFC 1925
Loading...