Advertisement

Overloaded Assignment Operator

Started by October 19, 2002 11:07 AM
4 comments, last by Kurioes 22 years ago
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.
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();

Advertisement
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)?
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.
Okay... how do I do this, and what do I have to be careful for?
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).

This topic is closed to new replies.

Advertisement