Conversion by constructor (C++ only)

A converting constructor is a single-parameter constructor that is declared without the function specifier explicit. The compiler uses converting constructors to convert objects from the type of the first parameter to the type of the converting constructor's class. The following example demonstrates this:

class Y {
  int a, b;
  char* name;
  Y(int i) { };
  Y(const char* n, int j = 0) { };

void add(Y) { };

int main() {

  // equivalent to
  // obj1 = Y(2)
  Y obj1 = 2;

  // equivalent to
  // obj2 = Y("somestring",0)
  Y obj2 = "somestring";

  // equivalent to
  // obj1 = Y(10)
  obj1 = 10;

  // equivalent to
  // add(Y(5))

The above example has the following two converting constructors:

The compiler will not implicitly convert types as demonstrated above with constructors declared with the explicit keyword. The compiler will only use explicitly declared constructors in new expressions, the static_cast expressions and explicit casts, and the initialization of bases and members. The following example demonstrates this:

class A {
  explicit A() { };
  explicit A(int) { };

int main() {
  A z;
//  A y = 1;
  A x = A(1);
  A w(1);
  A* v = new A(1);
  A u = (A)1;
  A t = static_cast<A>(1);

The compiler would not allow the statement A y = 1 because this is an implicit conversion; class A has no conversion constructors.

A copy constructor is a converting constructor.

Related information