What is Operator Overloading in C/C++

Operator overloading defines an additional meaning of operator.

Operator overloading is a feature of C++ programming language that allows a programmer to redefine the meaning of operator when they operate on class object.

What is Function?

Function is a named block of code that is used to perform some action when it is called in main() function.

Function has three parts in C/C++ language:

  1. Function declaration
  2. Function definition
  3. Function call

If you want to know more about functions, please read the following article.

What is Class?

Class may be defined as the collection of objects which have some properties and functions.

If you want to know more about classes, please read the following article.

What is ++ operator in C/C++ language?

It is increment operator. It is used to increase the value of any variable by 1.

For example:

int n = 1;
cout<<”Value before increment = “<<n;
n++;
cout<<”Value after increment = “<<n;

Value before increment = 1

Value after increment    = 2

There are two types of increment operator

  1. Pre-fix operator (++n)
  2. Post-fix operator (n++)

What is Operator Overloading?

In C++ language meaning of operators are already defined for example if we want to add two numbers we use + operator e.g.

int a, b, c;

c = a+b

a, b are the operands and + is the operator. When we add two integer numbers, computer already knows the function of + plus operator.

But what happen if we add two objects?

main()
{
Person obj1, obj2, obj3;
obj3 = obj1 + obj2;
}

Then system will show an error message. Because system doesn’t know what will happen when user adds two objects using plus operator.

Operator overloading defines an additional meaning of operator.

Operator overloading is a feature of C++ programming language that allows a programmer to redefine the meaning of operator when they operate on class object.

Operators that can be Overloaded

  1. Arithmetic Operators (+, -, *, /, %)
  2. Assignment Operator (=)
  3. Relational Operator ( ==, !=)
  4. Compound Assignment Operator (+=, -=, *=) etc.
  5. I/O operator ( <<, >>)
  6. Increment / Decrement Operator (++, –)
  7. Subscript Operator ( [] )
  8. Parenthesis Operator (())

Types of Operator that cannot be Overloaded

  1. Conditional Operator ( ?: )
  2. Member selection Operator ( . )
  3. Member selection operator with pointer to ( .* )
  4. Scope Resolution Operator ( :: )

How to Overload an Operator with Function?

Return_type operator_sign (parameter)
{
   //Body of Function
}

Some Rules for Operator Overloading

  • We cannot overload a new operator; we have to use existing operator.
  • We cannot change the number of operands that an operator takes.
  • We cannot change the working or operator.
  • The assignment operator ( = ) and address operator( &) do not need to be overloaded

Leave a Reply