2. Content
What is Overloading?
Types of Overloading.
Operator Overloading.
Types of Operator Overloading.
References
3. What is Overloading?
Multiple functions, Same Name ,
Different types or amount of Parameters.
Two Type is:-
1. Method Overloading
2. Operator Overloading.
4. Operator Overloading
“is a way of redefining the meaning of C#
operators”.
Done with special functions.
Can be Friend or Member Function.
5. Rules for Operator Overloading
Only Predefined Operator is Overloaded.
Cannot Change Operator Template.
Natural meaning and overloaded meaning
is same.
Must have a user defined operand.
8. Operator Overloading……
Syntax
modifiers type operator op(arglist)
{
Method body//task defined
}
9. Unary Operator Overloading
• You can declare your own version of the
increment (++) and decrement (--) operators.
• They must be public, static and unary.
• They can be used in prefix and postfix forms
Example:
10. Binary Operator Overloading
At least one parameter must be of the
enclosing type.
You may overload as many times as you
like with different parameter types.
You may return any type.
No “ref” or “out” parameters.
Two Types:-
1. Binary Arithmetic Operators
2. Binary Comparison Operators
11. Binary Arithmetic Operators
Operators + - * / % ^ & | << >>
One of the parameters must be of the enclosing type
// Class1 + Class1
public static Class1 operator+(Class1 lhs, Class1 rhs)
{
return new Class1(lhs.X + rhs.X);
}
// Class1 + int
public static Class1 operator+(Class1 lhs, int rhs)
{
return new Class1(lhs.X + rhs.X);
}
// int + Class1
public static Class1 operator+(int lhs, Class1 rhs)
{
return rhs + lhs;
}
Example
12. Binary Comparison Operators
Operators == != < <= > >=
Should return bool.
Must overload them in „PAIRS‟
public static bool operator <(Class2 lhs, Class2 rhs)
{
return new Class2(lhs.i < rhs.i);
}
Example
13. Determining Equality
Two kinds of comparison for objects:
Identity and equality
System.Object.Equals method
Equality operator(==)
public override bool Equals(Object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
}
Overloading is the idea of having multiple functons that are the same name. Each function must accept different types or amount of types. This is how the compiler differentiates from overloaded functions.