#### Archived

This topic is now archived and is closed to further replies.

This topic is 5603 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I want to overload the assignment operator. I have a "TIMER" class to measure the time between two frames (FPS meter, physics). I know it''s possible to do something as TIMER = float (although I doubt it''s usefullness ) but I want the opposite: float = TIMER. I figure the operator isn''t a member of the TIMER class anymore but that''s as far as I can get. In this case, my code will become cleaner (and less readable) but I want to know how to do this anyhow.

##### Share on other sites
You cannot overload operators for build in types, such as float. Why don''t you just use a member function, somthing like

float blah = TimerObject.GetTime();

Or you can overload the () operator, making it look like that:

float blah = TimerObject();

##### Share on other sites
I don''t really need it indeed, the assignment operator would call the member function anyway. I just wondered if it was possible (I thought so) and how.

But suppose I had a FLOAT class ... how would I do that (If it''s possible)?

Second, what should the () operator do (I mean, what does it normally do)?

##### Share on other sites
If you really want to use something like float=TIMER, you can also create a conversion-to-float operator for TIMER (TIMER::operator float() {...}), but you have to be careful with this.

##### Share on other sites
Okay... how do I do this, and what do I have to be careful for?

##### Share on other sites
TIMER::operator float(){   return (float)time_elapsed;  // return whatever value you need here...}

Note that you don''t define a return value (the function is assumed to return float).
The reason you might want to be careful with this is because this is quite simply a conversion from TIMER to float. Anywhere the compiler expects a float, and you accidently give it a TIMER, the compiler will use this conversion.
Personally, in your case, I''d use what Yann L suggested - a member function that returns the time. I''d use a conversion operator when it''s clear that my class can also be represented as another type (say... a conversion from MyInteger to int, or from Rational to double).