Operator overloading in C++

Introduction:

Operator overloading is one of the best features of C++. By overloading the operators, we can give additional meaning to the operators like +-*/=.,= etc., which by default are supposed to work only on standard data types like int, float, char, void etc. It is an essential concept in C++. It’s a type of polymorphism in which an operator is overloaded to give it the user-defined meaning.

C++ allows us to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading, respectively. The process of selecting the most suitable overloaded function or operator is called overload resolution.

Meaning of operators:

             An operator is a symbol that tells the compiler to perform specific mathematical, logical calculations or some other special operations.

Types of overloading: 

There are two types of overloading

1. Function overloading.

2. Operator overloading.

Meaning of function overloading:

The process of having two or more functions with the same name but with different parameters (arguments) is called function overloading. The function is redefined by either using different types of arguments or a different number of arguments. It is only through these differences that a compiler can differentiate between functions.

Meaning of Operator overloading:

      In C++, it can add special features to the functionality and behaviour of already existing operators like athematic and other operations. The mechanism of giving special meaning to an operator is known as operator overloading. For example, we can overload an operator ‘+’ in a class like string to concatenate two strings by just using +. 

Operations that can be perform:

     1.   Athematic operations: + – * / %

     2.  Logical operations:  && and ||

     3. Relational operations: == != >= <=

      4. Pointer operators: & and *

      5. Memory management operator: new, delete []

Implementing of Operator overloading:

1. Member function: It is in the scope of the class in which it is declared.

2. Friend function: It is a non-member function of a class with permission to access both private and protected members. 

Difference between Member and friend function:

Member function:

  1. The number of parameters to be passed is reduced by one, as the calling object is implicitly supplied s an operand.
  2. Unary operators tales no explicit parameters.
  3. Binary operators take only one explicit parameter.

Friend Function:

  1. More number of parameters can be passed.
  2. Unary operators take one explicit parameter.
  3. Binary operators take two explicit parameters.

Rules for Operator overloading:

  1. To work, at least one of the operand must be a user-defined class object.
  2. We can only overload the existing operators, Can’t overload new operators.
  3. Some operators cannot be overloaded using a friend function. However, such operators can be overloaded using the member function.

Disadvantages of an operator overloading:

In operator overloading, any C++ existing operations can be overloaded, but some exceptions are as follows:

  1.  Conditional [?:], size of, scope(::), Member selector(.), member pointer selector(.*) and the casting operators.
  2. We can only overload the operators that exist and cannot create new operators or rename existing operators.
  3. At least one of the operands in overloaded operators must be user-defined, which means we cannot overload the minus operator to work with one integer and one double. However, you could overload the minus operator to work with an integer and a mystring.
  4.  It is not possible to change the number of operands of an operator supports.
  5. All operators keep their default precedence and associations (what they use for), which cannot be changed.
  6. Only built-in operators can be overloaded.

Advantages:

  1. Operator overloading enables programmers to use notation closer to the target domain.
  2. Operator overloading provides similar support to built-in types of user-defined types.
  3. Operator overloading makes the program easier to understand.

The need for operator overloading:

It allows us to provide an intuitive interface to our class user, plus makes it possible for templates to work equally well with classes and built-in types. Operator overloading allows C++ operators to have user-defined meanings on user-defined types or classes.

Syntax for operator overloading:

Class class_name
	{
  		………………….
		…………………..
	Public 
		Return_type operator symbol (argument ())
		{
			……………….
			……………….
		}
	………………………….
};

Unary operators and binary Operator overloading:

Unary operators:

Operators which work on a single operand are called unary operators.

Examples: Increment operators(++), Decrement operators(–),unary minus operator(-), Logical not operator(!) etc…

Binary operators:

Operators which works on Two operands are called a binary operator.

Overloading special operators:

Some of the special operators in C++ are as follows:

  1. new – It is used to allocate the memory dynamically.
  2. Delete – It is used to free the memory dynamically.
  3. [] – It is a subscript operator.
  4. -> – – It is a member access operators.
  5. = – It is used to assign the values.
  6. () – It is used for function call.

The operators other than listed above can be overloaded either as a member or as non-members. But in general, non-member overloading is recommended. Because:

  1. Symmetry: When a binary operator is defined as a class method, it must have objects as its operands. We should write like complex*5 but not like 5*complex because 5.operator*(complex)does not make any sense. In other words, a*b should be the same as b*a. Otherwise, it breaks the cumulativeness that the user is expecting from the *operator. So, in this case, we should use no-member operators overloading.
  2. Weak coupling: since a non-member method cannot access private member, it tends to make the class less coupled

Example:

Using unary operator:
 //Overload ++ when used as prefix
#include<iostream.h>
Using namespace std;
Class count
{ 
 Private:
 Int value;
 Public:
//constructor to initialize count to 5
Count() : value(5)  {}
//overload ++ when used as prefix
Void operator ++ () 
{ 
++value;
}
Void display()
{
Cout<<”Count: “<<value<<endl;
}
};
Int main()
{
Count count1;
//call the “void operator ++ ()” function
++count1:
Count1.display();
Return 0;
}

Output:

Count:  6

Note:

Here, When we use ++count1; , the void operator ++() is called. This increases the value attribute for the object count1 by 1.

When we overload the operators, we can use it to work in any ways we like. For example, we could have used ++ to increase the value by 100.

However, this makes our code more confusing and difficult to understand. So using operators in overloading correctly and consistently, and understandably helps easy to understand without any difficulties.

The above-given example works when ++ is used as a prefix to make ++ works as a postfix; we use this syntax.

Syntax:

Here, the int inside the parentheses. It’s the syntax used for using unary operators as postfix; it’s not a function parameter.

Example 2: 

//C++ program to overload the binary operator +
//This program adds two complex numbers

#include<iostream.h>
using namespace std;
 class Complex
{
 Private:
  float real;
 float imag;
Public:
//constructor to initialize real and imag to 0
Complex() :  real(0), image(0)  {}
 void input()
{
 // overload the + operator
Complex operator + (const Complex7 obj)
{
Complex temp;
temp.real = real +obj.real;
temp.imag = imag +obj.imag;
return temp;
}

void output()
{
If(imag<0)
 Cout<< “OutputComplex number: ” << real << “i”;
else
count<< “Output Complex number: “<< “+” << “I”;
}
};
Int main()
{
Complex complex1, complex2,result;
Cout<< “Enter first complex number:\n;
Complex1.input();
Cout<< “Enter second complex number:\n”;
Complex2.input();

//complex1 calls the operator function
//complex2cis passed as an arguments to the function
result = complex1 + complex2;
result.output();
}

Output:

 Enter first complex number:

Enter real and imaginary parts respectively: 9 5

Enter second complex number:

Enter real and imaginary parts respectively: 7 ^

Output Complex number: 16+11i

In this program, the operator function is:

Complex operator + (const Complex7 obj)

We can also write this function like:

Complex operator + (Complex&nbsp; obj)
{
//code
}

Access specifiers:

Every member of a class is specified by 3 levels of access protections. These are used to define the scope of members of a class.

The access specifiers are indicated by using the keywords:

1. Private

2. Public

3. Protected

  1. Private: Private access means member data written under this section accessible by only member functions. They cannot be accessed from outside the class or anywhere in the program. If no access specifiers are mentioned, then by default, members are treated as private.
  2. Public: It means that members can be accessed by any function inside or outside the class, but within a program. The private variable height is accessed through the member function. Some of the public function of a class provides an interface for accessing the private and protected class members.
  3. Protected: The class members of this section are accessible by the member functions of the same class, friends of the class, and member functions derived from this class. The members cannot be accessed from outside; It is similar to the private members.

This brings us to the end of the blog on Operator Overloading in C++. Hope this helps you to up-skill your C++ skills. To learn more about programming and other related concepts, check out the courses on Great Learning Academy

Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro.

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

seventeen − 2 =