Curriculum
Course: Learn C++
Login

Curriculum

Learn C++

Text lesson

Introduction to Operator Overloading in C++

In this lesson, you will learn

  • Operator Overloading
  • Non Overloadable Operator
  • Types of Operator Overloading in C++

 

Operator Overloading

Operator overloading in C++ is a specific case of polymorphism in which the operator is overloaded to provide a special meaning to the objects of user-defined data types.

Basically, It adds some features or redefines the functionality of already existing operators.

To overload an operator, you define a function that specifies what should happen when that operator is used with objects of your class.

 

Example: We have three objects A, B, and C of the same class and we write C = A – B.

So, here we can redefine how the minus (-) operator works and we can write C = A – B, instead of writing C = A.subtract(B).

 

General Syntax

return-type operator op();

 

Syntax: Inside Class

return-type operator op(arglist)
{
      //Function Body
}

Here, the return-type may be built-in datatype or class-type, and op is the operator being overloaded. operator op is the function name and operator is a keyword.

 

Syntax: Outside Class

return-type classname :: operator op(arglist)
{
      //Function Body
}

 

 

 


 

Non Overloadable Operator

1. Dot operator or class member access operator ( . ).

2. Scope Resolution Operator (::)

3. Pointer to Member Operator (.*).

4. Conditional or Ternary Operator (?:)

 

 

 


 

Types of Operator Overloading

  1. Unary Operator Overloading
  2. Binary Operator Overloading

 

Unary Operator Overloading

An operator that contains only one operand or works on only one operand is known as a unary operator overloading. E.g. Increment or Decrement operator.

There are two ways to do operator overloading.

 

1. Using Class Function

Syntax

return-type operator op();

 

2. Using Friend Function

Syntax

friend return-type operator op(arglist);

 


 

Binary Operator Overloading

 

An operator that contains two operands or works on two operands is known as a binary operator overloading. (e.g., +, -, *, /)

 

Syntax

 

1. Using Class Function

 

return-type operator op(arguments);

 

2. Using Friend Function

 

friend return-type operator op(argument1, argument2);

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review