# Thread: operator int()

1. ## operator int()

the book im reading has an exercise to make a class Int and overload the basic operators. there is 2 things i dont understand. it asks for bounds checking, but i dont know why the answer in the back of the book needs to convert it to long double. the other thing i dont get is 'operator int()'. when does this come in play in the class? its a conversion from Int to type int, i know that much. but when is this operator called. thanks in advance for responses
Code:
```//////////////////////////class Int/////////////////////////
class Int
{
private:
int i;
public:
Int(): i(0)  //set default value (constructor)
{	}

Int(int integer):	i(integer)	  //1-arg constructor
{	}

void put_int()			//display int
{ cout << i << endl; }

void get_int()	//get int
{ cin >> i; }

operator int()   //conversion operator from Int to int
{	return i;	}

Int operator + (Int i2)
{	return limit_check(long double(i) + long double(i2));	}

Int operator - (Int i2)
{	return limit_check(long double(i) - long double(i2));	}

Int operator * (Int i2)
{	return limit_check(long double(i) * long double(i2));	}

Int operator / (Int i2)
{	return limit_check(long double(i) / long double(i2));	}

Int limit_check(long double num)
{
if(num > 2147482648.0L || num < -2147482648.0L)
{
cout << "\nOverflow error:  Exiting." << endl;
exit(1);
}

return Int(int(num));
}

};

/////////////////////////////////////////////////////////////```

2. when is this operator called
It is called when a variable of type int is expected. For example:
Code:
```void func(int nParam)
{
}

int main()
{
Int a=5;

func(a);
}```
In this case 'a' will call operator int() to resolve itself to type 'int'. Quite ingenious really.

3. >>Int a=5;
int a=5;

Geez.

4. Maybe you misunderstand, XSquared. Int is a class.

5. Whoops. You're right. Name your clases differently, geez!

6. Originally Posted by bennyandthejets
In this case 'a' will call operator int() to resolve itself to type 'int'. Quite ingenious really.
thanks for the reply.
why is it required to convert it to long double and check the bounds?

7. Name your clases differently, geez!
I agree. I would have called it CInt.

why is it required to convert it to long double and check the bounds?
I don't know, it does seem a bit pointless doesn't it.

Popular pages Recent additions