Operator Overloading in C++

In this tutorial we will study and understand the concept and application of Operator Overloading in C++

Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type. For example ‘+’ operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) or even a user defined class object.

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

Operator Overloading in C++ Syntax
Implementing Operator Overloading

Operator overloading can be done by implementing a function which can be :

Operator overloading function can be a member function if the Left operand is an Object of that class, but if the Left operand is different, then Operator overloading function must be a non-member function. Operator overloading function can be made friend function if it needs access to the private and protected members of class.

Operator Overloading using Member Function Example Program

Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below

Run Online

Output
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Operator Overloading using Friend Function Example Program

In this program we are overloading the negation operator to work on our class object named xyz. It will perform negation of all data member values of our class just like it works on basic data types.

Run Online

Output
XYZ please
3 4 5
BEFORE OVERLOADING
3
4
5
AFTER OVERLOADING
-3
-4
-5
Operators That Cannot be overloaded
  • scope operator – ::
  • sizeof
  • member selector – .
  • member pointer selector – *
  • ternary operator – ?:
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *