LeastSquaresWonderer
LeastSquaresWonderer

Reputation: 540

Why does constructor work with wrong parameters?

I have a constructor

T(someClass<double> o);

The class someClass is initialized by double* x. That is

someClass<double>(double * X);

Why does the following work?

double * X=new X[10];
T obj(X);

Why does this work, even though that there is no constructor for T, that takes double * as an argument (it should get an instance of someClass)? Does the compiler implicitly initialize someClass, from double*?

Upvotes: 1

Views: 41

Answers (1)

songyuanyao
songyuanyao

Reputation: 173024

someClass<double>(double * X); could be regarded as converting constructor, which could convert double* to someClass<double> implicitly.

For T obj(X);, the compiler will check all the possible constructors of T to construct obj; and might find a possible way that implicitly converts X to someClass<double> and then use it as the argument for T(someClass<double> o).

You can prohibit unintended implicit conversion by making the constructor explicit.

Upvotes: 5

Related Questions