Reputation: 8357
Implementing conversion from custom class to POD or other types are quite simple. It's implemented in the custom class itself as a operator named after the destination type. Like this,
operator int{ return anInt; }
How about the other way around? Can I overload for example, int to custom class type cast?
Upvotes: 0
Views: 215
Reputation: 490408
You can, but you do it differently, by providing a constructor for your class that takes the basic type as a parameter:
class X {
public:
X(int) {}
};
void f(X const &x) { }
int main(){
f(2); // allowed -- will construct an X, then pass it to `f`.
}
Note that this can lead to unexpected conversions in some cases -- it's often considered better to mark such constructors as explicit
to prevent them from being used except when you explicitly force the conversion.
Upvotes: 2
Reputation: 103733
Use a single argument constructor
MyClass(int n) :anInt(n) {}
Upvotes: 1