Converting constructor - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# Converting constructor

From cppreference.com
< cpp‎ | language

A constructor that is not declared with the specifier explicit and which has one non-default parameter (until C++11) is called a converting constructor

Unlike explicit constructors, which are only considered during direct initialization (which includes explicit conversions such as static_cast), converting constructors are also considered during copy initialization, as part of user-defined conversion sequence.

It is said that a converting constructor specifies an implicit conversion from the types of its arguments to the type of its class. Note that non-explicit user-defined conversion function also specifies an implicit conversion.

Implicitly-declared and user-defined non-explicit copy constructors and move constructors are converting constructors.

### [edit] Example

Run this code

    struct A
    {
        A(int) {} // converting constructor
        A(int, int) {} // converting constructor (C++11)
    };

    struct B
    {
        explicit B(int) {}
        explicit B(int, int) {}
    };

    int main()
    {
        A a1 = 1; // OK: copy-initialization selects A::A(int)
        A a2(2); // OK: direct-initialization selects A::A(int)
        A a3 {4,5}; // OK: direct-list-initialization selects A::A(int, int)
        A a4 = {4,5}; // OK: copy-list-initialization selects A::A(int, int)
        A a5 = (A)1; // OK: explicit cast performs static_cast, direct-initialization

    //  B b1 = 1; // Error: copy-initialization does not consider B::B(int)
        B b2(2); // OK: direct-initialization selects B::B(int)
        B b3 {4,5}; // OK: direct-list-initialization selects B::B(int, int)
    //  B b4 = {4,5}; // Error: copy-list-initialization does not consider B::B(int,int)
        B b5 = (B)1; // OK: explicit cast performs static_cast, direct-initialization
    }

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/language/converting_constructor&oldid=78050"