What is a Binary Operator in C++?
In C++,Binary Operator Overloading allows you to redefine how operators work for custom types, especially for operations involving two operands. These operators are categorised into various types based on their functionality, such as mathematical, logical, and relational operators.
1. Mathematical Binary Operators
These operators perform arithmetic operations on numeric values or custom types that represent numbers. Common examples include:
- + (addition)
- - (subtraction)
- * (multiplication)
- / (division)
- % (modulus)
2. Logical Binary Operators
These operators perform logical operations on boolean values or custom types that return boolean-like results. Common examples include:
- && (logical AND)
- || (logical OR)
- ! (logical NOT)
3. Relational Binary Operators
These operators are used to compare two operands. They return a boolean value indicating the result of the comparison. Common examples include:
- == (equal to)
- != (not equal to)
- < (less than)
- > (greater than)
- <= (less than or equal to)
- >= (greater than or equal to)
What is Operator Overloading?
Operator Overloading in C++ refers to the ability to redefine the functionality of operators for user-defined types. While C++ unary operator overloading is commonly used for simple operations like increment or decrement, overloading binary operators allows you to define operations for complex numbers, such as specifying how to add two class objects representing complex numbers using the + operator.
Types of Operator Overloading in C++
In C++, Operator Overloading can be categorised into two main types:
- Unary Operator Overloading: This involves operators that operate on a single operand (e.g., increment ++, decrement --).
- Binary Operator Overloading: This involves operators that operate on two operands (e.g., addition +, subtraction -).
Rules to Define the Operator Function
When defining an operator function in C++, specific rules must be followed:
- The function must be defined within a class.
- The keyword operator must precede the operator symbol being overloaded.
- The return type must be specified.
- The function can take one or more parameters, depending on whether it is unary or binary.
What is Binary Operator Overloading?
A binary operator is an operator that operates on two operands. In C++, binary operators can be overloaded to provide custom functionality for user-defined types.
Syntax of Binary Operator Overloading
ReturnType ClassName::operator Symbol(const ClassName& obj) {
// implementation
}
- ReturnType: The type returned by the overloaded operator function.
- ClassName: The class name for which the operator is being overloaded.
- Symbol: The overloaded operator (e.g., +, -, *, etc.).
- obj: The right operand passed as an argument.
Redefinable Binary Operators
Binary Operators that can be overloaded in C++:
1. Arithmetic Operators
Operator |
Name |
* |
Multiplication |
*= |
Multiplication/assignment |
+ |
Addition |
+= |
Addition/assignment |
- |
Subtraction |
-= |
Subtraction/assignment |
/ |
Division |
/= |
Division/Assignment |
% |
Modulus |
%= |
Modulus/assignment |
2. Relational & Logical Operators
Operator |
Name |
< |
Less than |
<= |
Less than or equal to |
> |
Greater than |
>= |
Greater than or equal to |
== |
Equality |
!= |
Inequality |
&& |
Logical AND |
3. Bitwise Operators
Operator |
Name |
& |
Bitwise AND |
&= |
Bitwise AND/assignment |
^ |
Exclusive OR |
^= |
Exclusive OR/assignment |
<< |
Left shift |
<<= |
Left shift/assignment |
>> |
Right shift |
>>= |
Right shift/assignment |
4. Assignment Operators
Operator |
Name |
= |
Assignment |
+= |
Addition/assignment |
-= |
Subtraction/assignment |
*= |
Multiplication/assignment |
/= |
Division/assignment |
%= |
Modulus/assignment |
&= |
Bitwise AND/assignment |
^= |
Exclusive OR/assignment |
<<= |
Left shift/assignment |
>>= |
Right shift/assignment |
5. Pointer Operators
Operator |
Name |
. |
Member selection |
->* |
Pointer-to-member selection |
6. Other Operators
Operator |
Name |
, |
Comma |
= |
Assignment |
Binary Operator Overloading Algorithm
To implement Binary Operator Overloading in C++, you need to define a member function that specifies how the operator should behave for user-defined types. The algorithm involves specifying the operator, defining the parameters it takes (usually another instance of the same class), and then implementing the logic to perform the desired operation, returning a new instance or modifying the existing one as needed. This approach enables the intuitive use of standard operators with custom objects, enhancing code readability and functionality.
Algorithm of Binary Operator Overloading
CLASS Complex
CONSTRUCTOR Complex(FLOAT r, FLOAT i)
FUNCTION operator+(Complex obj) RETURNS Complex
FUNCTION display()
MAIN
c1 = NEW Complex(real1, imag1)
c2 = NEW Complex(real2, imag2)
c3 = c1 + c2
c3.display()
Binary Operator Overloading Algorithm in C++
To perform Binary Operator Overloading in C++ use the binary operator overloading algorithm:
- Identify the Operator and Class: Select a binary operator such as +, -, * on a class. Check if the operator is relevant to the operations defined by that class.
- Declare the Operator Function: Inside this class, declare the operator function using the keyword operator followed by the symbol of the operator (e.g., operator+, operator-). This function describes how the operator would works for that class.
- Define Parameters: The operator function generally is supposed to have at least one parameter representing the right-hand operand of the operation. The left-hand operand is *this where the operator is being invoked.
- Implement the Logic: Inside the operator function, provide the logic to understand the interaction of the two operands. This involves manipulating the operands' member variables and returning a new object of the same class with a result.
- Ensure Correct Return Type: The type returned by the function must have to match the type of operation resultant. It is usually a new object returned by value of the same class.
- Test the Overloaded Operator: Having written the overloaded operator code, the operator can then be tested with different objects to see whether it works properly and gives correct results.
Example Programs of Binary Operator Overloading in C++
Here are the C++ Programs for Binary Operator Overloading:
Example 1: Performing all mathematical operations on two objects
#include <iostream>
using namespace std;
class Math {
int num;
public:
// Set value
void setValue(int val) { num = val; }
// Overload + operator
Math operator + (Math& obj) {
Math temp;
temp.num = num + obj.num;
return temp;
}
// Overload - operator
Math operator - (Math& obj) {
Math temp;
temp.num = num - obj.num;
return temp;
}
// Overload * operator
Math operator * (Math& obj) {
Math temp;
temp.num = num * obj.num;
return temp;
}
// Overload / operator
Math operator / (Math& obj) {
Math temp;
temp.num = num / obj.num;
return temp;
}
// Display value
void display() const {
cout << num << endl;
}
};
int main() {
Math obj1, obj2, result;
obj1.setValue(20);
obj2.setValue(10);
cout << "Obj1: ";
obj1.display();
cout << "Obj2: ";
obj2.display();
// Perform and display operations
result = obj1 + obj2;
cout << "Obj1 + Obj2: ";
result.display();
result = obj1 - obj2;
cout << "Obj1 - Obj2: ";
result.display();
result = obj1 * obj2;
cout << "Obj1 * Obj2: ";
result.display();
result = obj1 / obj2;
cout << "Obj1 / Obj2: ";
result.display();
return 0;
}
Output
Obj1: 20
Obj2: 10
Obj1 + Obj2: 30
Obj1 - Obj2: 10
Obj1 * Obj2: 200
Obj1 / Obj2: 2
Explanation
This program demonstrates operator overloading by defining a Math class with overloaded +, -, *, and / operators. These operators perform arithmetic operations on two Math objects. The setValue method assigns values to objects, and the display method shows the result of each operation.
Example 2: Complex Number Addition using Operator Overloading in C++
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Overload + operator
Complex operator+(const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
// Display function
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4); // Example complex number 3 + 4i
Complex c2(1, 2); // Example complex number 1 + 2i
Complex c3 = c1 + c2; // Using overloaded + operator
c3.display(); // Output: 4 + 6i
return 0;
}
Explanation
- The complex class has private members to store the real and imaginary parts.
- The constructor initializes these members.
- The overloaded + operator adds two Complex objects together and returns a new Complex object.
- The display() function prints the complex number in standard form.
- In main(), two complex numbers are created, added using the overloaded operator, and displayed.
Output
4 + 6i
Example 3: Adding and Subtracting Complex Numbers in C++
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor to initialize real and imaginary parts
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Overload + operator
Complex operator+(const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}
// Overload - operator
Complex operator-(const Complex& obj) {
return Complex(real - obj.real, imag - obj.imag);
}
// Display function
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(5, 7); // 5 + 7i
Complex c2(3, 4); // 3 + 4i
Complex sum = c1 + c2; // Using overloaded + operator
Complex diff = c1 - c2; // Using overloaded - operator
cout << "Sum: ";
sum.display(); // Output: Sum: 8 + 11i
cout << "Difference: ";
diff.display(); // Output: Difference: 2 + 3i
return 0;
}
Explanation
In this program, we define a complex class to represent complex numbers. The operator+ and operator- functions are overloaded to perform addition and subtraction of two complex numbers. The display() function outputs the complex number in standard form. Two complex numbers are created in the main() function, and their sum and difference are calculated and displayed.
Output
Sum: 8 + 11i
Difference: 2 + 3i
Example 4: Adding Two Vectors in C++
#include <iostream>
using namespace std;
class Vector {
private:
float x, y;
public:
// Constructor to initialize vector components
Vector(float xCoord = 0, float yCoord = 0) : x(xCoord), y(yCoord) {}
// Overload + operator for vector addition
Vector operator+(const Vector& obj) {
return Vector(x + obj.x, y + obj.y);
}
// Display function
void display() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Vector v1(3.5, 2.5); // Vector (3.5, 2.5)
Vector v2(1.5, 4.5); // Vector (1.5, 4.5)
Vector result = v1 + v2; // Using overloaded + operator
cout << "Resultant Vector: ";
result.display(); // Output: Resultant Vector: (5.0, 7.0)
return 0;
}
Explanation
In this example, we define a Vector class representing a two-dimensional vector with x and y components. The operator+ function is overloaded to combine two vectors by summing their respective elements. The display() function outputs the vector in coordinate form. In the primary () function, two vectors are created and added using the overloaded operator, and the resultant vector is displayed.
Output
Resultant Vector: (5.0, 7.0)
Example 5: Overloading the Addition Operator for a Point Class
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
Point operator + (const Point& p) {
return Point(x + p.x, y + p.y);
}
void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(3, 4), p2(1, 2), result;
result = p1 + p2;
result.display(); // Output: (4, 6)
return 0;
}
Explanation
The above program overloaded + operator adds two Point objects' x and y coordinates in the Point class. In the main() function, two Point objects (p1 and p2) are created with coordinates (3, 4) and (1, 2) respectively. The overloaded + operator adds these two points, resulting in a new Point object with coordinates (4, 6). The display() function then prints this result.
Output
(4, 6)
Example 6: Overloading the Multiplication Operator for a Matrix Class
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
public:
vector<vector<int>> data;
Matrix(int rows, int cols, vector<vector<int>> values) : data(values) {}
Matrix operator * (const Matrix& m) {
vector<vector<int>> result = data; // Assume matrix dimensions match
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < m.data[0].size(); j++) {
for (int k = 0; k < data[0].size(); k++) {
result[i][j] += data[i][k] * m.data[k][j];
}
}
}
return Matrix(data.size(), m.data[0].size(), result);
}
void display() {
for (auto& row : data) {
for (auto& val : row) {
cout << val << " ";
}
cout << endl;
}
}
};
int main() {
Matrix m1(2, 2, {{1, 2}, {3, 4}});
Matrix m2(2, 2, {{5, 6}, {7, 8}});
Matrix result = m1 * m2;
result.display(); // Output: 19 22 43 50
return 0;
}
Output
19 22
43 50
Explanation
In the Matrix class, the overloaded * operator performs matrix multiplication. The main() function creates two 2x2 matrices (m1 and m2). The multiplication of these matrices results in another matrix where each element is the sum of the products of corresponding elements from the rows of the first matrix and columns of the second. The display() function outputs this result.
Example 7: Performing Arithmetic Operations by Overloading Multiple Binary Operators
#include <iostream>
using namespace std;
class Math {
int num;
public:
Math(int val) : num(val) {}
Math operator + (const Math& m) { return Math(num + m.num); }
Math operator - (const Math& m) { return Math(num - m.num); }
Math operator * (const Math& m) { return Math(num * m.num); }
Math operator / (const Math& m) { return Math(num / m.num); }
void display() { cout << num << endl; }
};
int main() {
Math obj1(10), obj2(5), result(0);
result = obj1 + obj2; result.display(); // Addition
result = obj1 - obj2; result.display(); // Subtraction
result = obj1 * obj2; result.display(); // Multiplication
result = obj1 / obj2; result.display(); // Division
return 0;
}
Output
15
5
50
2
Explanation
In the Math class, the overloaded operators +, -, *, and / perform arithmetic operations on two objects. The main() function creates two Math objects (obj1 with value 10 and obj2 with value 5). Each result is displayed after performing addition, subtraction, multiplication and division operations.
Example 8: C++ Unary Operator Overloading
#include <iostream>
using namespace std;
class Counter {
int count;
public:
Counter() : count(0) {}
// Overload ++ operator
Counter operator++() {
Counter temp;
temp.count = ++count; // Pre-increment
return temp;
}
void display() {
cout << "Count: " << count << endl;
}
};
int main() {
Counter c1;
++c1; // Using overloaded ++ operator
c1.display(); // Output: Count: 1
return 0;
}
Output
Count: 1
Explanation
This code demonstrates a C++ unary operator overloading. The pre-increment operator (++) is overloaded to increase the count in the Counter class. Using ++c1 increments the value and displays 1 as the output.
Conclusion
In conclusion, the Binary Operator Overloading in C++ allows custom behaviour for operators like +, -, *, etc., when applied to user-defined types. This enhances code readability and makes object manipulation more intuitive. By overloading operators, you can define how objects interact in expressions, improving the natural use of classes. However, ensuring consistency with expected behaviours and avoiding unnecessary overloading is crucial.
Master Industry-Relevant Skills in College for Your Tech Career Success!
Explore ProgramFrequently Asked Questions
1. What are the two types of Method Overloading?
i) By Number of Parameters: Functions have the same name but different numbers of parameters.
Example: void show(int); void show(int, double);
ii) By Type of Parameters: Functions have the same name but different types of parameters.
Example: void show(int); void show(double);
2. What is Unary and Binary Operator Overloading in C++?
- Unary: Works with one operand (e.g., ++, - -,!).
- Binary: Works with two operands (e.g., +, -,*).
3. What are binary operations in C++?
Binary operations in C++ are operations that involve two operands
These can be used for arithmetic, relational, logical, or bitwise operations.
Examples of binary operations:
i) Arithmetic: +, -, *, /, %
Example: a + b (adds two numbers)
ii) Relational: ==, !=, <, >, <=, >=
Example: a == b (checks if a equals b)
iii) Logical: &&, ||
Example: (a > b) && (c < d) (logical AND)
iv) Bitwise: &, |, ^, <<, >>
Example: a & b (bitwise AND)