views:

82

answers:

1

I understand the use of the explicit keyword to avoid the implicit type conversions that can occur with a single argument constructor, or with a constructor that has multiple arguments of which only the first does not have a default value.

However, I was wondering, does a single argument constructor with a default value behave the same as one without a default value when it comes to implicit conversions?

+3  A: 

The existence of a default value does not stop the single-argument ctor from being used for implicit conversion: you do need to add explicit if you want to stop that.

For example...:

#include <iostream>

struct X {
  int i;
  X(int j=23): i(j) {}
};

void f(struct X x) {
  std::cout << x.i << std::endl;
}

int main() {
  f(15);
  return 0;
}

compiles and runs correctly:

$ g++ -Wall -pedantic a.cc
$ ./a.out
15
$ 

correctly, that is, if you want an int to become a struct X implicitly. The =23 part, i.e. the default value for the one argument to the constructor, does not block this.

Alex Martelli
After all, a single argument constructor with a default value is a "single argument constructor"...
Matthieu M.