6

If I have a class A, and I write A(5);, it clearly makes a temporary variable.

But what is not clear if A(5); is a constructor call (using 5 as parameter), or if this is a function style cast, casting 5 to A. Can someone explain it to me please?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
andre3312
  • 147
  • 7

1 Answers1

8

It's a functional-style type conversion which creates a t from an int by calling the constructor. There is no way to explicitly call a constructor in C++.

This is described in [expr.type.conv] (N3337):

5.2.3 Explicit type conversion (functional notation)

1) A simple-type-specifer (7.1.6.2) or typename-specifer (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4). If the type specified is a class type, the class type shall be complete. If the expression list specifies more than a single value, the type shall be a class with a suitably declared constructor (8.5, 12.1), and the expression T(x1, x2, ...) is equivalent in effect to the declaration T t(x1, x2, ...); for some invented temporary variable t, with the result being the value of t as a prvalue.

Since t is a simple-type-specifier, this is equivalent to the corresponding cast expression. This is allowed to carry out the equivalent of a static_cast ([expr.cast]/4), which defines the final result of the conversion:

[expr.static.cast]/4: Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193