Constructor Type Coercion in C++
- by Robert Mason
Take the following class:
class mytype {
double num;
public:
mytype(int a) {
num = sqrt(a);
}
void print() {
cout << num;
}
}
Say there is a method which takes a mytype:
void foo(mytype a) {
a.print();
}
Is it legal c++ (or is there a way to implement this) to call foo(4), which would (in theory) output 2? From what I can glean you can overload type casts from a user defined class, but not to. Can constructor do this in a standards-compliant manner (assuming, of course, the constructor is not explicit). Hopefully there is a way to in the end have this legal:
int a;
cin >> a;
foo(a);
Note: this is quite obviously not the actual issue, but just an example for posting purposes. I can't just overload the function because of inheritance and other program-specific issues.