coderz.py

Keep Coding Keep Cheering!

Operator Overloading in C++

Accessing Elements
What is Operator Overloading?

Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the user-defined data type with a special meaning. Most of the operators available in C++ are overloaded or redefined using operator overloading. It’s used to run an operation on a user-defined data type.

Operators that can be overloaded:
  • Binary Arithmetic     ->     +, -, *, /, %
  • Unary Arithmetic     ->     +, -, ++, —
  • Assignment     ->     =, +=,*=, /=,-=, %=
  • Bitwise      ->     & , | , << , >> , ~ , ^
  • Dereferencing     ->     (->)
  • Dynamic memory allocation and Deallocation     ->     New, delete 
  • Subscript     ->     [ ]
  • Function call     ->     ()
  • Logical      ->     &,  | |, !
  • Relational     ->     >, < , = =, <=, >=

There are, however, a few operators who cannot be overloaded. The operators which are not overloaded are as follows:

  • scope operator -::
  • sizeof
  • member selector -.
  • member pointer selector – *
  • ternary operator – ?:
Operator Overloading Syntax:
return_type class_name  : : operator op(argument_list)  
{  
     // body of the function.  
}  
Implementation of Operator Overloading:

Operator overloading can be accomplished by implementing the following function:

  • Member Function
  • Non-Member Function
  • Friend Function
Overloading Rules for Operators:
  • Existing operators can only be overloaded, whereas new operators cannot.
  • At least one operand of the user-defined data type is present in the overloaded operator.
  • The friend function cannot be used to overload specific operators. The member function, on the other hand, can be used to overload those operators.
  • When unary operators are overloaded via a member function, they take no explicit arguments, but when overloaded via a friend function, they take one argument.
  • When binary operators are overloaded via a member function, they take one explicit argument; when they are overloaded via a friend function, they take two explicit arguments.

Note: also read about Virtual Destructors in C++

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

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

Advertisement