ITP

BCA - OOPS and Data Structures

What is operator overloading ? Rules with Example

In : BCA Subject : OOPS and Data Structures

Operator overloading means giving new meaning to an existing operator.

  • Operator Overloading gives new meaning to existing operators.

  • Used to make operations on objects easier and more natural .

  • Must follow rules — only existing operators, at least one user-defined operand, some operators can’t be overloaded.

  • Can be done using member functions or friend functions .

Rules of Operator Overloading in C++

 

1. Only existing operators can be overloaded**  
   You cannot create new operators. Only existing ones like `+`, `-`, `*`, `==`, etc., can be overloaded.

2. At least one operand must be of user-defined type**  
   You cannot overload operators for built-in types only (e.g., you can't change how `int + int` works). At least one operand should be a class/object.

3. Some operators cannot be overloaded**  
   The following operators **cannot** be overloaded:
   - Scope resolution operator `::`
   - Member selection operator `.`
   - Pointer-to-member operator `.*`
   - Ternary operator `?:`

4. You cannot change precedence and associativity of operators**  
   Even after overloading, the order in which expressions are evaluated remains the same.

5. Operator overloading function must be either a:**
   - **Member function** of a class, or
   - **Friend function** of the class

6. Overloaded operators should work intuitively**  
   Although not a rule, it's a best practice to make the behavior of the operator match its usual meaning (e.g., `+` should perform addition).

About us

A truly open platform where you may ask questions and get answers. We also provide comprehensive and easy-to-understand answers to question papers.  discover...

Site status

Flag Counter

Privacy Policy

Sitemap