C++ Operator Overloading With Programming Examples

C++ Operator Overloading

Table of Contents

C++ Operator Overloading:

The feature in C++ programming that allows the programmer to redefine the meaning of operators when they operate on class objects is known as operator overloading.

OR

Defining a new job for the existing operator with respect to the class objects is called operator overloading.

C++ Operator Overloading is one of the most important features of object-oriented programming. The operators in c++ are implemented as functions. Therefore, C++ Operator Overloading works very similar to function overloading. In function overloading, we learn that we can create multiple functions of the same name that work differently depending on parameter types. C++ Operator Overloading allows the programmer to change the behavior of the operator to perform different operations depending on the type of operands.

We can redefine or overload most of the built-in operators available in C++. Thus we can use operators with user-defined types as well.

Some of the important operators that can be overloaded in C++ are as follows:

  • Arithmetic operators +, -, *, / and %.
  • Assignment operator (=).
  • Relational or comparison operators == and !=.
  • Compound assignment operators +=, -=, *=, /=, %=.
  • I/O operators (<<, >>).
  • Subscript operator([])
  • Parenthesis operator ( () ).

The operators that cannot be overloaded are as follows:

  • ?: (conditional)
  • .(member selection)
  • .*(member selection with pointer to member)
  • :: (scope resolution)
  • sizeof(object size information)
  • typeid(object type information).



Rules and Restrictions on C++ Operator Overloading:

Following are some important rules and restrictions on C++ Operator Overloading:

  • we cannot create a new operator, only existing operators can be overloaded.
  • We cannot change the number of operands that an operator takes. For example, overloaded unary operators remain unary operators and overloaded binary operators remain binary operators. Operators &, *, + and – all have both unary and binary versions. These unary and binary versions can be separately overloaded.
  • We cannot change the working of an operator by C++ Operator Overloading. For example, we cannot make the + operator as a subtract operator.
  • The related operators, like * and *=, must be overloaded separately.
  • The precedence of an operator cannot be changed by overloading. However, parentheses can be used to force the order of evaluation of overloaded operators in an expression.
  • The associatively of an operator cannot be changed by overloading.
  • The assignment operator (=) and address operator (&) do not need to be overloaded. Because these two operators are already overloaded in c++ library. For example: if obj1 and obj2 are two objects of the same class then, we can use code obj1 = obj2; without overloading = operator. This code will copy the contents of obj2 to obj1. Similarly, we can use the address operator directly without overloading which will return the address of the object in memory.

Operator Function:

An operator is overloaded by declaring a special member function of the class known as operator function. This member function is defined inside the class using the keyword ‘operator’ followed by the symbol of the operator to be overloaded.

The general syntax to define the operator function is as follows:

return-type operator sign (parameter list)

{

Body of function

}

Where

Return-type:

It indicates the type of value returned by the member function. If function returns anything, then keyword ‘void’ is used.

Operator:

It is a keyword of C++. It indicates the operator function.

Sign:

It is the sign or symbol of operator that is to be overloaded.

Parameter list:

It indicates the arguments that are passed to the function. When this operator function is called, the operations are performed on those arguments that are passed to the function.


Overloading the Arithmetic Operators:

Some of the most commonly used operator in c++ are the arithmetic operator +, -, *, and /. Please note that all of the arithmetic operator are binary operators. These operators are overloaded to increase their capabilities and enable them to work with user define objects in the same way as they work with the basic data types (such as int, long, and float etc).

Example Write a program that adds and subtracts two integer values using binary C++ Operator Overloading:

c++ Operator Overloading

Programming Explanation:

In this program, the class temp has one data member ‘data’ of integer data type. It also has four member function getvalue() to get data from user, display() to display data, and two operator function that are used to overload addition and subtraction operator.

In the main function, four objects of class temp are declared (created). The values are taken from user for both of the objects using getvalue() member function. Then the data of the objects are added and subtracted using overloaded addition and subtraction operator respectively. The result of addition is stored in object ‘sum’ and result of subtraction is store in object ‘sub’. These results of addition and subtraction are displayed on the screen using display() member function.

The values stored in objects obj1, obj2, sum, and sub of class temp are shown in the following figures:

c++ Operator Overloading

The value of 20 and 10 are input in objects obj1 and obj2 respectively. After executing + overloaded operator, the value of data of object ‘sum’ (that is the object of temp class) becomes 20. Similarly, after the execution of – overloaded operator, the value of data of object ‘sub’ (that is also an object of temp class) is 10. The value of data of ‘sum’ and ‘sub’ are displayed using the display() function.


Example write a program using class distance that creates an object and gets value from user in feet and inches. It then adds these values with the values of another object by overloading of + operator:

OutPut:

Programming Explanation:

In this program, class string has a data member ‘str’ of string type. The member function input() takes string from user and function ‘print()’ displays on the screen. The + operator function concatenates the strings of both the objects.

In the main() function, two objects of class string type are created. The strings in data member ‘str’ of ‘s1’ and ‘s2’ are entered. These strings are concatenated (combined) using statement s3= s1+s2. The + operator function concatenates the string s1 and s2, and stores the concatenated string in s3.



Overloading I/O operators:

I/O operator are stream extraction operator >> and the stream insertion operator <<, c++ is able to input and output the built-in data types using these operators. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like and object.

Overloading operator << and overloading operator >> are similar  to overloading operator +. These are binary operators. But in overloading operator <<, the left operand is the ‘cout’ object and the right operand is the class object. The ‘cout’ is actually an object of type ostream. Similarly, in overloading operator >>, the left operand is the cin object and the right operand is the class object cin which is an object of type istream.

The general syntax for overloading I/O operator is as follows:

Return-type operator sign (parameter list)

{

Body of function

}

Where

Return-type:

It indicates the return type of overloaded I/O operator. The return type for overloaded stream extraction operator is ostream& and for overloaded stream insertion operator is istream&.

Operator:

It is a keyword of C++. It indicates the operator function.

Sign:

It indicates the sign of overloaded I/O operator. The sign for overloaded stream extraction operator is << and overloaded stream insertion operator is >>.

Parameter list:

There are two parameters for overloaded I/O operators. The first is of ostream type for stream extraction overloading and istream type for stream insertion overloading, and the second is of that class whose object is used.

How to displaying class data using stream extraction overloading operator:

c++ Operator Overloading

Programming Explanation:

In this program, each object of student contains the roll no and marks. In the main() function, the statement “cout<<s1;” invokes(calls) the overloaded stream extraction operator that displays the record of student or roll number 1. Similarly, the statement “cout<<s2;” displays the record of student or roll number 2. It displays the chain of roll no, and marks by only using single statement in the main function.

Example write program which take record of two employees using overloaded stream insertion operator, and display them on screen using stream extraction overloading operator:

c++ Operator Overloading

Programming Explanation:

In this program, two I/O operator overloaded functions in ‘employee’ class are defined. C++ Operator Overloading function of stream insertion operator ( >> ) is defined to input data for data member of class ‘employee’. The C++ Operator Overloading function of stream extraction operator (<<) is defined to show the record of employee.

In the main() function, two objects of class employee are declared. The statement cin<<e1; invokes the overloaded stream insertion operator that takes input  for first employee’s record from user, and the statement cin>>e2; takes input for second record. The records of both the employees are displayed using overloaded stream extraction.


Overloading Comparison Operators:

There are various relational operators supported by C++ language like(<, >, <=, >=, ==, etc) which can be used to compare C++ built-in data types. Comparison operators are binary operators. A comparison operator compares two operands, and returns true or false depending on the result. These operators can be overloaded which can be used to compare the objects of a class.

Example write a program that compares distances using overloaded comparison operator:

OutPut:

Programming Explanation:

in this program, the class ‘distance’ contains two data members, feet and inches. It also contains an C++ Operator Overloading function which compares two distances and returns 1 if both of the values of data members of object 1 is less than the value of data member of object 2, otherwise 0.

In the main() function, two objects of class distance are declared. The statement d1<d2 calls the C++ Operator Overloading function and returns the value on the basis of the values of their data members.

Example write a program that compares the length of two string that either they are equal or not using overloaded comparison operator:

c++ Operator Overloading

Programming Explanation:

In this program, the class ‘mystring’ have two data members: str of string type and len of int type. The == operator overloading  function compare the strings length if they are equal then it returns 1 otherwise it returns 0.

In the main() function, two objects of class ‘mystring’ are declared. The statement “if(s1==s2) calls (invokes) the C++ Operator Overloading function and return value on the basis of the values of their data members. Because the length of these string is different, so value 1 (true value) will be returned.


C++ Overloading Unary Operators:

The unary operators operate on a single operand. Following are some examples of unary operators:

  • The increment (++) and decrement (–) operators.
  • The unary plus (+) operator.
  • The unary minus(-) operator.
  • The logical not (!) operator.

All these operands are implemented in an identical manner. The unary operator operates on the object for which it was called. Normally, this operator appears on the left side of the object such as !obj, -obj, and ++obj but sometime it can be used as postfix as well such as obj++ or  obj–

Example write a program to explain prefix and postfix increment operator using operator function:

c++ Operator Overloading

Programming Explanation:

In this program, the class incre has a data member ‘data’ which is set to zero in default constructor. There are two operator functions: one for prefix increment and second for postfix increment the int inside the bracket of postfix increment operator function is used to give information to the compiler that it is the postfix version of the operator. It does not indicate the integer.

In the main() function, an object ‘obj’ is declared of class ‘incre’ type. The statement “++obj ” call (invokes) the operator function “void operator ++()”, and display() function of the object displays the result on the screen. The statement “obj++” invokes the operator function “void operator ++(int) ” and the display() function of the object displays result on the screen.

Example write a program to explain prefix and postfix decrement operator using operator function:

c++ Operator Overloading

Programming Explanation:

In the above program, the class ‘decre’ has a data member ‘data’ which is set to zero in default constructor. This class has two operator function one for prefix increment and second for postfix decrement. The function in which int is inside the bracket is the postfix decrement operator function, and the other operator function in prefix decrement operator function.

In the main() function, two objects obj and obj1 are declared of class ‘decre’ type. The statement ‘obj1= –obj” invokes the C++ Operator Overloading function ‘decre operator –()’ stores the result in obj1, and then displays on the screen. While the statement ‘obj1 = obj– ‘ invokes the C++ Operator Overloading function ‘decre operator –(int)’ stores the result in obj1, and then displays on the screen.



Overloading Subscript Operator:

The subscript operator is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.

The subscript operator is typically overloaded to provide direct access to the private one-dimensional array that is the data member of the class. Single parameter is passed using subscript operator [].

In C++ Operator Overloading function of subscript operator, the operator []is returning a reference because operator [] has higher precedence even than assignment operator, that’s why function should return the actual array element, so that other operation could perform on actual array element.

One of the advantages of overloading the subscript operator is that we can make it safer than accessing arrays directly. Normally, when accessing arrays, the subscript operator does not check whether the index is valid or not.

Example write a program to explain the overloading of the subscript operator []:

c++ Operator Overloading

Programming Explanation:

In the above program, the class ‘saferarry’ has an array that is initialized the values equal to their index number in default constructor. The class has a subscript operator function that returns the value of the index of an array that is given as parameter to the function. It also shows a message on invalid index number.

In the main() function, an object a of class ‘saferarray’ type is declared. Three output statements are also given to show the values of different elements of array. First statement displays the value of third element of array, while the second statement displays a message ‘index out of bound’ because the index is out bound and displays the value of a[12] as 0.

Overloading Parenthesis Operator:

All of the overloaded operator that we have discuses earlier, take either one parameter or two parameters. Their number of parameters is fixed. But the overloaded parenthesis operator () does not fix any number of parameters. It allows taking any number of parameters (one, two, multiple, or no parameter).

Overloaded subscript operator [] provides the direct access to the private one-dimensional array, but overloaded parenthesis operator () provides access to the private two-dimensional array as it supports the passing of two index as parameters.

Example write a program to explain the overloading of parenthesis operator () using parenthesis operator function having two parameters and no parameter:

c++ Operator Overloading

Programming Explanation:

In the above program, the class matrix has a data member of two-dimensional array data[4][4]. The class has a default constructor that sets all the values of all the indexes of the two-dimensional array to zero. This class has two C++ Operator Overloading functions for parenthesis operator, one of them take two parameters, row and column and returns the value to that index form the 2-D array, and second C++ Operator Overloading function has no parameter, it sets the array to zero, working the same way as default constructor.

In the main() function, an object m is declared of class ‘matrix’ type. It sets the value 4.5 to data[1][2] using two parameters parenthesis operator function, and displays in on the screen. Then it erases the array using operator function with no parameter and displays the same index on the screen.


Related Article:

C++ Destructor And Difference Between Constructor And Destructor

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: