As far as I have used "converting constructors" they look like this:
struct X {
X(A); // conversion from A -> X
X(B,C = someC); // conversion from B -> X, with some default C
};
X x1 = A(); // calls X::X(A())
X x2 = B(); // calls X::X(B(),someC)
This makes perfect sense, and as far as I know works as long as you don't have a constructor:
struct Y {
Y(A,B); // no implicit conversion
};
However, this is where it gets interesting, the C++11 standard reads literally:
12.3.1 Conversion by constructor
- A constructor declared without the function-specifier
explicit
that can be called with a single parameterspecifies a conversion from thetype of its first parametertypes of its parameters to the type of its class. Such a constructor is called a converting constructor.
(italics were originally underlined, but markdown doesn't accept <u>
)
This seems to suggest that it was changed that a converting constructor doesn't have to be callable "with a single parameter" and the change from "type of its first parameter" to "types of its parameters" (note the plural!) further supports this. While I would expect that "type of its first parameter" would be changed to "type of its single non-optional parameter" (1) or even "type of its parameter that received an explicit argument" (2) in order to allow these:
struct Z {
Z(A = a, B, C = c); // (1)
Z(D = d, E = e, F = f); // (2)
};
Z = D(); // (2)
Z = E(); // (2)
I don't see how the formulation with the plural form makes sense: Does it really indicate you can perform conversion with several arguments? What does this mean?
A conversion constructor is a single-parameter constructor that is declared without the function specifier explicit . The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor's class.
A conversion constructor is any non- explicit constructor callable with one argument. In your code sample, as the Complex constructor provides default values for its parameters, it can be called with a single argument (say 3.0 ).
Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes.
You can define a member function of a class, called a conversion function, that converts from the type of its class to another specified type.
The language was modified as part of the addition of initializer lists. See n2672: init-list wording.
An example:
struct S {
S(int x, double y) { }
};
void f(S) { }
int main() {
f({ 42, 42.0 });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With