I have a custom class that acts as an int called Integer, I would like to tell compiler how to convert certain types to Integer automatically so that I can avoid typing same
Write a constructor that takes int
, as:
class Integer
{
public:
Integer(int);
};
If the class Integer
has this constructor, then you can do this:
void f(Integer);
f(Integer(1)); //okay
f(1); //this is also okay!
The explanation is that when you write f(1)
, then the constructor of Integer
that takes a single argument of type int
, is automatically called and creates a temporary on the fly and and then that temporary gets passed to the function!
Now suppose you want to do exactly the opposite, that is, passing an object of type Integer
to a function takes int
:
void g(int); //NOTE: this takes int!
Integer intObj(1);
g(intObj); //passing an object of type Integer?
To make the above code work, all you need is, define a user-defined conversion function in the class as:
class Integer
{
int value;
public:
Integer(int);
operator int() { return value; } //conversion function!
};
So when you pass an object of type Integer
to a function which takes int
, then the conversion function gets invoked and the object implicity converts to int
which then passes to the function as argument. You can also do this:
int i = intObj; //implicitly converts into int
//thanks to the conversion function!