It's not really neccessary to use overloading, but it can make your code easier to read and keep consistent. Look at the following example -
Code:
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
class MyInt
{
private:
int theInt;
public:
MyInt(int b):theInt(b){}
MyInt operator+(MyInt &b)const{
return MyInt(theInt+b.Get());
}
int add(MyInt b)const{
return theInt+b.Get();
}
void Print()const{
cout << theInt;
}
void Set(int b){
theInt=b;
}
int Get()const{
return theInt;
}
friend ostream& operator<<(ostream& os,MyInt i){
return os << i.theInt;
}
};
int main(){
//With operator overloading
MyInt a=10;
MyInt b=20;
MyInt c=30;
MyInt d = a+b+c;
cout << a << "+" << b << "+" << c << "=" << d << "\n";
//Without operator overloading
a.Set(10);
b.Set(20);
c.Set(30);
d.Set(a.Get()+b.Get()+c.Get());
a.Print();
cout.put('+');
b.Print();
cout.put('+');
c.Print();
cout.put('=');
d.Print();
cout.put('\n');
return 0;
}
Which one is easier to understand doing a quick scan of the code?