Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from built in types to Custom Classes

Tags:

c++

casting

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.

like image 566
Hamza Yerlikaya Avatar asked Nov 29 '22 18:11

Hamza Yerlikaya


2 Answers

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!   
like image 155
Nawaz Avatar answered Dec 05 '22 03:12

Nawaz


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

like image 35
Fred Larson Avatar answered Dec 05 '22 01:12

Fred Larson