2

Possible Duplicate:
What is the difference between (type)value and type(value)?

If you have a function that takes an argument of type b, but at the call site you only have a variable of type a. Is there a difference between casting the function parameter from a to b, and constructing type b.

The specific example I am interested in is when there is no user defined cast operator, but there is a single argument constructor.

Example:

Function definition:

void DoWork(const B &arg1);

In my specific example type a is const char *

Call site:

DoWork((B)"Hello");

vs

DoWork(B("Hello"));

B class definition

class B
{
public:
    B() : m_szValue(){}
    B(const char *szValue) { strcpy (m_szValue, szValue); }
private:
    char m_szValue[MAX_VALUE_LEN + 1];
};
Community
  • 1
  • 1
Peter Nimmo
  • 1,045
  • 2
  • 12
  • 25

1 Answers1

3

Writing a C-style cast (T)x, where x is of type U, more or less tries the following in order:

  1. If T and U are of class type, look for a conversion operator U::operator T() const or a one-argument constructor T::T(U).

  2. If T and U are primitive types, apply the standard value conversions (int to double, etc.).

  3. reinterpret_cast<T>(x).

Note that you mustn't have both a conversion operator and implicit conversion construction, though, or the call will be ambiguous.

[Correction/Clarification:] There is no difference between T(x) and (T)x.[/] You can even say DoWork("Hello"); on account of the implicit conversion provided by the one-argument constructor. (Do disallow this sneaky behaviour, declare the constructor explicit, as is often a good idea for one-argument constructors.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • This is misleading / wrong: in fact, there is *no* difference at all between the C-style cast and the function-style cast (except for syntax). They are identical in every respect; not only in OP’s code, but everywhere. – Konrad Rudolph Sep 19 '11 at 10:42
  • @Konrad: Hm... which aspect of this is *wrong*, though? The C-style cast achieves what any of the listed constructions achieve, don't they? The point is that it subsumes various conversions as well as reinterpretation, which you can control explicitly with the C++ constructions. – Kerrek SB Sep 19 '11 at 10:45
  • @Your answer strongly implies that `T(x)` sometimes has a different meaning than `(T)x`. At least that’s how I would understand your answer. You explicitly said “ *in your code* there is no difference” (emphasis mine) and while that’s true, it’s also an irrelevant detail. There is no difference, full stop. – Konrad Rudolph Sep 19 '11 at 10:49
  • @Konrad: I see, good point, let me reword that. – Kerrek SB Sep 19 '11 at 10:52
  • @Konrad: Check it out now, I hope this is more accurate! – Kerrek SB Sep 19 '11 at 10:58
  • Already checked, already voted up. – Konrad Rudolph Sep 19 '11 at 11:02