Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a cast or a construction?

I'm a little confused after reading something in a textbook. Regarding the code:

void doSomeWork(const Widget& w)
{
    //Fun stuff.
}

doSomeWork(Widget(15));

doSomeWork() takes a const Widget& parameter. The textbook, Effective C++ III, states that this creates a temporary Widget object to pass to doSomeWork. It says that this can be replaced by:

doSomeWork(static_cast<Widget>(15));

as both versions are casts - the first is just a function-style C cast apparently. I would have thought that Widget(15) would invoke a constructor for widget taking one integer parameter though.

Would the constructor be executed in this case?

like image 514
John Humphreys Avatar asked Sep 30 '11 14:09

John Humphreys


1 Answers

In C++ this kind of expression is a form of a cast, at least syntactically. I.e. you use a C++ functional cast syntax Widget(15) to create a temporary object of type Widget.

Even when you construct a temporary using a multi-argument constructor (as in Widget(1, 2, 3)) it is still considered a variation of functional cast notation (see 5.2.3)

In other words, your "Is this a cast or a construction" question is incorrectly stated, since it implies mutual exclusivity between casts and "constructions". They are not mutually exclusive. In fact, every type conversion (be that an explicit cast or something more implicit) is nothing else than a creation ("construction") of a new temporary object of the target type (excluding, maybe, some reference initializations).

BTW, functional cast notation is a chiefly C++ notation. C language has no functional-style casts.

like image 72
AnT Avatar answered Sep 17 '22 14:09

AnT