Reputation: 623
I was looking forward to remove ambiguity between normal constructor and auto-conversion constructor.
as far as I know this ambiguity can be partially removed by declaring normal constructor as explicit
so compilers will avoid using this constructor as conversion constructor like following:
#include <iostream>
#include <fstream>
class Integer{
int i ;
public:
explicit Integer (const int _i) : i(_i) {} //Normal constructor
Integer (const int& ii ) : i (ii) {} // conversion constructor
operator int() {return int (i) ;} // Auto-conversion operator
friend std::ostream & operator <<(std::ostream &os, const Integer io ) {
std::cout << io.i ;
return os ;
}
};
int main() {
// Integer io (5); call of overloaded ‘Integer(int)’ is ambiguous error
Integer io2 = 20 ; // conversion constructor
std:: cout << io2 << "\n" ;
int i = io2 ; // auto-conversion operator
std:: cout << i << "\n" ;
}
output :
20
20
my questions are:
1- Is there a standard way to force using a constructor as conversion constructor, since there is a standard way to force usage as normal constructor?
2- is it a good practice to use conversion constructor and autoconversion operators, in another words can I ensure that different compilers will use the constructor as conversion constructor in case if normal contructor is not overloaded with conversion constructor ?
My thanks
Upvotes: 4
Views: 667
Reputation: 1153
Is there a standard way to force using a constructor as conversion constructor, since there is a standard way to force usage as normal constructor?
Yes, you omit the explicit
keyword.
is it a good practice to use conversion constructor and autoconversion operators, in another words can I ensure that different compilers will use the constructor as conversion constructor in case if normal contructor is not overloaded with conversion constructor ?
If the compiler is standards compliant, then there are no issues here. There's nothing wrong with implicit constructions. They can be quite handy when you're constructing literal arrays of objects and such. Can also be surprising. Use your judgement.
Upvotes: 1