How it works...

To understand why explicit constructors are necessary and how they work, we will first look at converting constructors. The following class has three constructors: a default constructor (without parameters), a constructor that takes an int, and a constructor that takes two parameters, an int and a double. They don't do anything, except printing a message. As of C++11, these are all considered converting constructors. The class also has a conversion operator that converts the type to a bool:

    struct foo     {       foo()      { std::cout << "foo" << std::endl; }      foo(int const a)      { std::cout << "foo(a)" << std::endl; }      foo(int const a, double const b)      { std::cout << "foo(a, b)" << std::endl; }       operator bool() const { return true; }  }; ...

Get Modern C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.