You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names: the keyword “operator” followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Operator Overloading Rules:
- At least one argument of an overloaded operator must be of a class type
- An overloaded operator can be a friend of a class
- New operators cannot be created
- The number of arguments for an operator cannot be changed
- The precedence of an operator cannot be changed
- ., ::, *, and ? cannot be overloaded
Unary Operators Overloading
- The unary operators operate on a single operand and following are the examples of Unary operators −
- The increment (++) and decrement (–) operators.
- The unary minus (-) operator.
- The logical not (!) operator.
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
Member_Function_Declarations
….
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
Binary Operators Overloading
The binary operators take two arguments and following are the examples of Binary operators. You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator.
class Box
{double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
Member_Function_Declarations
….
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
Input/Output Operators Overloading
C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object.
Here, it is important to make operator overloading function a friend of the class because it would be called without creating an object.
class Distance
{private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
Member_Function_Declarations….
friend ostream &operator<<( ostream &output, const Distance &D ){
output << “F : ” << D.feet << ” I : ” << D.inches;
return output;
}
friend istream &operator>>( istream &input, Distance &D )
{
input >> D.feet >> D.inches;
return input;
}
};