Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49329

Conversion from built in types to Custom Classes

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 thing over and over again,

someCall(Integer(1), Integer(2));

would become

someCall(1,2);

I've googled but all I could find is to do the oposite, casting Integer to int I would like to accomplish the opposite.

Upvotes: 4

Views: 4069

Answers (3)

O.C.
O.C.

Reputation: 6819

Nawaz has given the correct answer. I just want to point out someting. If the conversion operator is not const, you can't convert const objects

const Integer n(5);
int i = n; // error because non-const conversion operator cannot be called

Better declare your conversion operator as

operator int() const {return value;}

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

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!   

Upvotes: 14

Fred Larson
Fred Larson

Reputation: 62063

You could define constructors in Integer for those types you want to implicitly convert. Do not make them explicit.

Upvotes: 5

Related Questions