C++ Operator Overloading with Examples

What is Operator Overloading?

Using operator overloading in C++, you can specify more than one meaning for an operator in one scope. The purpose of operator overloading is to provide a special meaning of an operator for a user-defined data type.

With the help of operator overloading, you can redefine the majority of the C++ operators. You can also use operator overloading to perform different operations using one operator.

Syntax

To overload a C++ operator, you should define a special function inside the Class as follows:

class class_name
{
    ... .. ...
    public
       return_type operator symbol (argument(s))
       {
           ... .. ...
       } 
    ... .. ...
};

Here is an explanation for the above syntax:

  • The return_type is the return type for the function.
  • Next, you mention the operator keyword.
  • The symbol denotes the operator symbol to be overloaded. For example, +, -, <, ++.
  • The argument(s) can be passed to the operator function in the same way as functions.

Example 1

#include <iostream>
using namespace std;
class TestClass {
private:
	int count;
public:
	TestClass() : count(5) {}
	void operator --() {
		count = count - 3;
	}
	void Display() { 

		cout << "Count: " << count; }
};

int main() {
	TestClass tc;
	--tc;
	tc.Display();
	return 0;
}

Output:

 Operator Overloading

Here is a screenshot of the code:

 Operator Overloading

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Include the std namespace in our program to use its classes without calling it.
  3. Create a class named TestClass.
  4. Use the private access modifier, which marks a class member as privately accessible.
  5. Create an integer variable count. This variable will be privately accessible.
  6. Use the public access modifier, which marks a class member as privately accessible.
  7. Use a class constructor to initialize the variable counter to 5.
  8. Overload the meaning of the — operator.
  9. The operator will decrement the value of the variable x by 1.
  10. End of the operator overloading section. The operator has been given a new name.
  11. Defining a function named Display() function.
  12. Print the value of variable count alongside other text on the console when the Display() function is called. The } marks the end of the body of Display() function.
  13. End of the class body.
  14. Call the main() function. The program logic should be added within this function.
  15. Create an instance of the class TestClass and give it the name tc.
  16. This will call the void operator –() function.
  17. Use the stance of TestClass Class to call the Display() function.
  18. The function must return value upon successful completion.
  19. End of the body of the function main().

Different Approaches to Operator Overloading in C++

You can perform operator overloading by implementing any of the following types of functions:

  1. Member Function
  2. Non-Member Function
  3. Friend Function
  • The operator overloading function may be a member function when a Left operand is an object of the Class.
  • When the Left operand is different, the Operator overloading function should be a non-member function.

You can make the operator overloading function a friend function if it needs to access the private and protected class members.

Can all C++ Operators be Overloaded?

No. There are C++ operators that can’t be overloaded.

They include:

  • :: -Scope resolution operator
  • ?: -ternary operator.
  • . -member selector
  • Sizeof operator
  • * -member pointer selector

Things to Remember

  1. With operator overloading, you can redefine the way an operator works only for the user-defined types (objects, structures). You cannot use it for built-in types (float, char, int, etc.).
  2. The = and & C++ operators are overloaded by default. For example, you can copy the objects of the same Class directly using the = operator.
  3. Operator precedence doesn’t change the associatively and precedence of operators. However, you can change the order of evaluation using parenthesis.
  4. There are four operators that you cannot overload in C++. They include the scope resolution operator (::), member selection operator (.), member selection through a pointer to function operator (.*), and the ternary operator (?:).

Rules for Operator Overloading

Here are rules for Operator Overloading:

  • For it to work, at least one operand must be a user-defined class object.
  • You can only overload existing operators. You can’t overload new operators.
  • Some operators cannot be overloaded using a friend function. However, such operators can be overloaded using member function.

How to Overload Operator

Example 1

#include <iostream>   
using namespace std;
class OperatorOverload {
private:
	int x;

public:
	OperatorOverload() : x(10) {}
	void operator ++() {
		x = x + 2;
	}
	void Print() {
		cout << "The Count is: " << x;
		}
};
int main() {
	OperatorOverload ov;
	++ov;   
	ov.Print();
	return 0;
}

Output:

Overload Operator Example

Here is a screenshot of the code:

Overload Operator Example

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Include the std namespace in our program to use its classes without calling it.
  3. Create a class named OperatorOverload.
  4. Use the private access modifier, which marks a class member as privately accessible.
  5. Create an integer variable x. This variable will be privately accessible.
  6. Use the public access modifier, which marks a class member as privately accessible.
  7. Use a class constructor to initialize variable x to 10.
  8. Overload the meaning of the ++ operator.
  9. The operator will increment the value of variable x with 2.
  10. End of the operator overloading section. The operator has been given a new name.
  11. Calling the Print() function.
  12. Print the value of variable x alongside other text on the console when the Print() function is called.
  13. End of the body of the Print() function.
  14. End of the class body.
  15. Call the main() function. The program logic should be added within this function.
  16. Create an instance of the OperatorOverload Class named ov.
  17. This will call the void operator ++() function.
  18. Use the stance of OperatorOverload class to call the Print() function.
  19. The function must return value upon successful completion.
  20. End of the body of the function main().

Example 2

#include<iostream> 
using namespace std;

class TestClass {
private:
	int real, over;
public:
	TestClass(int rl = 0, int ov = 0) {
		real = rl;
		over = ov;
	}

	TestClass operator + (TestClass const &obj) {
		TestClass result;
		result.real = real + obj.real;
		result.over = over + obj.over;
		return result;
	}
	void print() {
		cout << real << " + i" << over << endl;
	}
};
int main()
{
	TestClass c1(9, 5), c2(4, 3);
	TestClass c3 = c1 + c2;
	c3.print();
}

Output:

Overload Operator Example

Here is a screenshot of the code:

Overload Operator Example

Code Explanation:

  1. Including the iostream header file into our program in order to use its functions.
  2. Include the std namespace into our program in order to use its classes without calling it.
  3. Create a class named TestClass. The { marks the beginning of the class body.
  4. Use the private access modifier to mark variables as private, meaning they can only be accessed from within the Class.
  5. Define two integer variables, real and over.
  6. Use the public access modifier to mark the constructor as public, meaning that it will be accessible even outside the Class.
  7. Creating the class constructor and initializing the variables.
  8. Initialize the value of variable real.
  9. Initialize the value of the variable over.
  10. End of the constructor body.
  11. Override the meaning of the + operator.
  12. Create the data type result of type TestClass.
  13. Use the + operator with complex numbers. This line will add the real part of a number to the real part of another number.
  14. Use the + operator with complex numbers. This line will add the imaginary part of a number to the imaginary part of another number.
  15. The program will return the value of the variable result upon successful execution.
  16. End of the definition of the new meaning of + operator, that is, overloading.
  17. Call the print() method.
  18. Print the new complex number after addition on the console.
  19. End of the body of print() function.
  20. End of the body of TestClass Class.
  21. Calling the main() function.
  22. Passing the values of both real and complex parts to be added. The first part of c1 will be added to the first part of c2, that is, 9+4. The second part of c1 will be added to the second part of c, that is, 5+3.
  23. Performing an operation using the overloaded + operator and storing the result in variable c3.
  24. Printing the value of variable c3 on the console.
  25. End of the body of main() function.

Summary

  • You can specify more than one meaning for a C++ operator in one scope.
  • This is called operator overloading.
  • Operator overloading provides a special meaning of an operator for a user-defined data type.
  • You can redefine the majority of C++ operators through operator overloading.
  • Not all C++ operators can be overloaded.
  • For an operator to be overloaded, at least one of the operands must be a user-defined object.
  • Only existing operators can be overloaded. You cannot overload new operators.