Explain how overloading a unary operator is almost similar to overloading a binary operator with necessary examples and include main() function to demonstrate. Mention the differences between these two in terms of number of operands they deal with.
Hello! In general, both the overloading a unary operator and overloading a binary operator have similar signature:
(data type) operator(symbol of operator) (input parameters)
{
//some code here
}
For example:
class Point
{
public:
int x;
int y;
Point(int x_, int y_) :x(x_), y(y_) {}
Point operator+(Point second_number) // operator+ receives two arguments: this and second_number
{
return Point(this->x * second_number.x, this->y * second_number.y);
}
};
This function overload a binary operator “+” and returns the object of Point with x = the product of the this->x and the second_num.x and y = the product of the this->.y and the second_num.y.
int main() {
Point a(1, 2);
Point c = c + a; // it's equals to c.operator+(a);
return 0;
}
But this is not a good example of overloading. It makes our code more incomprehensible, because user don’t expect that operator + will work like a multiplication We only use the overloading operators when it will make code easier and understandable. For example, we can overload operator + to calculating vector’s sum. (Because user will expect this)
The main difference between overloading a unary operator and overloading a binary operator is the number of input arguments. Overloading a binary operator requires two arguments, while overloading a unary one only one argument.
Point operator!() //only one argument - this
{
return Point(-this->x, -this->y);
}
Unary operators: ++, --, !, ~, [], *, &, ()
Binary operators: +, -, *, /, %, ==, !=, >, <, >=, <=, &&, ||, &, |, ^, <<, >>, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, ->, ->*, (,), ","
Comments
Leave a comment