Overload (programming): Difference between revisions

Content deleted Content added
Overloading Methods: Disambiguation link repair - You can help!
Line 10:
==Overloading Operators ==
 
It is also possible to overload operators (such as plus, minus, multiply, divide), comparisons ( such as >, <, =), input and output, et al. Overloading operators serves a purpose when performing math and other operations on uncommon types, especially user defined [[data types]]. One could overload the addition operator to add two dates together (in the context of the following one would be adding two time spans together, not necessarily actual dates, and the code doesn't allow for months with less than 31 days). This would be accomplished by something similar to the following [[syntax]] (in C++):
 
Date Date::operator+(int Month, int Day, int Year)
{
Date temp;
temp.Year += Year;
temp.Day += Day;
if temp.Day > 31
{
temp.Day - 31;
temp.Month + 1;
}
temp.Month += Month;
if temp.Month > 12
{
temp.Month - 12;
temp.Year + 1;
}
}
 
TheAddition previousis codea sample[[binary couldoperation|binary]] beoperation, confusingwhich becausemeans it doesn'thas explain where thea left and right [[operandsoperand]] are. In C++, the ''temp'' object in this case is the left operand and the parametersarguments being passed are the right operands. Note that a [[unary operation|unary]] operator would recieve no arguments since it doesn't have any operands.
 
AThe [[compiler]] would be able to differentiate the two addition operators because one is passed three parameters instead of the normal addition which is passed just one. As mentioned above however, methods are overloaded based on their number AND type of parameters.
Another overloaded addition operator could be overloaded with three parameters IF the data types passed are different too. The compiler would differentiate those two by their data types. The following shows how it would be setup using an [[angle]] as a data type with [[Degree_(angle)|Degree]]-[[minute of arc|Minute]]-[[arcsecond|Second]] notation ''within the same program''.
 
Angle Angle::Operator+(double Degree, double Minutes, double Seconds)