Operator Overloading: Need and Rules of Operator Overloading in C++

 Operator Overloading: 

Need and Rules 

 

·       Operator Overloading allows to redefine the meaning of an operator (like +, -, <<, ++, etc.) for user-defined types (classes/structs).

·       Helps make code natural


 

Need of Operator Overloading

1. To Make User-Defined Types Behave Like Built-In Types

 

Example:

Complex c1(2,3), c2(4,5);

Complex c3 = c1 + c2;   // natural & readable

 

Without operator overloading, :-

c1.add(c2);

This is less intuitive.

 

2. To Improve Readability & Maintainability

Writing a + b, a * b, a == b is cleaner and feels mathematical.

 

3. To Support Operator Functionality for Custom Classes

E.g., vectors, matrices, strings, time classes, dates, and currency types.

 

4. To Integrate Objects with C++ Standard Library

<< overloading use:

cout << object;

 

5. Supports Abstraction & Encapsulation

Users can use operators without knowing internal implementation details.


 

Rules of Operator Overloading

Rule 1: Only existing operators can be overloaded

Do not create a new operator like $$, **, <>.


Rule 2: At least one operand must be a user-defined type

Do not overload operators for built-in types only.

Not allowed: int operator+(int, int);


Rule 3: Precedence, associativity & arity( number of arguments) cannot be changed

Not change how the compiler groups operators.


Rule 4: Do not change the number of operands

Unary and binary nature stays the same.


Rule 5: Some operators cannot be overloaded

Not allowed to overload:

Operator

Reason

.

Member access

.*

Pointer to member

::

Scope resolution

?:

Ternary operator

sizeof

Compile time

typeid

RTTI


Rule 6: Overloading cannot change operator behaviour drastically

Meaning should remain natural.


Rule 7: Overloading does not give new syntax

Not do: obj =+ 5;   // wrong


Rule 8: Friend functions can be used to overload operators

Used when the left operand is not the calling object.


Rule 9: Some operators must be overloaded as member functions

Like:

  • = (assignment)
  • () (function call)
  • [] (array subscript)
  • -> (member access)

 

Different Ways to Overload Operators

1. Member Function Overloading

The operator works on the current object (LHS).


2. Friend Function Overloading

Used when the LHS operand is not an object of the class.


Post a Comment

0 Comments