Difference between (long) x and long(x)?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have never fully understood what the difference is between these two forms
of casting. Can anyone please clarify? long is a primitive data type so no,
it's not calling a class constructor. This is not simply a .NET feature
either, also works in VS6.
 
mosimu said:
I have never fully understood what the difference is between these two forms
of casting. Can anyone please clarify? long is a primitive data type so no,
it's not calling a class constructor. This is not simply a .NET feature
either, also works in VS6.

Besides syntax, there is no difference. There's no difference when ctors are
involved, either. Of course, you can't do things like (char*) x using the
functional notation, and you can't creating temporaries using T() or T(x,y)
with the cast notation. But for single argument ctors, the functional and
cast notations are equivalent.
 
For primitive types like long it doesn't matter. But if you had a class
foo then:

(foo) x calls x's conversion function.
foo (x) calls foo's contructor.

Ramsey
 
Ramsey said:
For primitive types like long it doesn't matter. But if you had a class
foo then:

(foo) x calls x's conversion function.
foo (x) calls foo's contructor.

Nope. It's spelled out as I described in the C++ Standard, 5.2.3. The two
expressions you gave mean the same thing. Either can call a foo ctor or an x
conversion function. Here's an example:

struct X
{
operator int();
};

struct Y
{
Y(const X&);
};

void f(X x)
{
int i1 = (int) x;
int i2 = int(x);

Y y1 = (Y) x;
Y y2 = Y(x);
}
 
Back
Top