My question is regarding data type conversion in c++. Does c++ provides a implicit conversion for built-in data types ( int, float) to user defined data types?
In the following example, I am trying to add a double ( t4 = t3 + 1.0) with test object type and its working fine using + operator so is the double implicitly converted to test type object?
class test {
double d;
int m;
public:
test() {
d=0;
m=0;
}
test(double n) {
d=n;
}
const test operator+(const test& t) {
test temp;
temp.d = d+ t.d;
return temp;
}
};
int main() {
test t1(1.2);
test t2(2.5);
test t3, t4;
t3= t1+ t2;
t4 = t3 + 1.0;
return 0;
}
The constructor
test(double n)declares an implicit conversion fromdoubletotest. In general, any constructor that is callable with exactly one argument (that includes constructors that can take more arguments, but have default-values for those), can be used as an implicit conversion, unless it is markedexplicit:Edit:
t4 = 1.0 + t3does not work, because you have overloaded youroperator+as a member-function, and thus it is only considered if the first operand is of the typetest– implicit conversion are not tried in this case. To make this work, make your operator a free function: