Home > SparkCharts > Cs > C++ > Operator Overloading

C++


 
 

Operator Overloading

Use operator overloading to replace existing behaviors of a class or to specify a method for an object with no predefined method for a given operator. In order to overload the (), [], and -> operators, you must use a class member. You can overload other operators using non-member functions if the leftmost operand is of the same class type. If it is of a different type, then you must overload the operator as a non-member function. If that operator function needs to access private or protected members, then the operator should also be declared as a friend function.

Examples of member and non-member overloaded operators:

class Classname {
public:
   bool operator==(Classname &c) /*Function for a Member
Operator*/
   {
         code
   }
   friend istream & operator <<(istream&, Classname &); /*
Function Prototype for a Friend non-member function*/
};
istream & operator <<(istream &is, Classname &c) /* Function for
non-member friend overload*/
{
   code
}
bool operator==(Classname & c_one, Classname &c_two) /*Non-member
operator overload*/
{
   code
}