Conversion constructors (C++ only)
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. The following example demonstrates this:
class Y {
int a, b;
char* name;
public:
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))
add(5);
}
The above example has the following two conversion constructors:Y(int i)
which is used to convert integers to objects of class Y.Y(const char* n, int j = 0)
which is used to convert pointers to strings to objects of class Y.
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 {
public:
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 conversion constructor.
Related information