You are on page 1of 5

Operator Overloading

Intro..
Mechanism of giving special meaning to an operator is known as operator overloading We can overload all C++ operators except:
Class member access operators (.,.*) Scope resolution operator (::) Size operator (sizeof) Conditional operator (?:)

Defining operator overloading


Use operator function
return-type classname :: operator(op-arglist) { Function body //task definition }

The overloading process involves:


1. 2. 3.
op x or x op x op y

Create a class that defines the data type that is to be used in the overloading operation Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function Define the operator function to implement the required operations
for unary operator interpreted as operator op(x) for friend functions for binary operators interpreted as x.operator op (y) for member function operator op(x,y) for friend functions

Overloaded operator functions can be invoked as

Overloading Unary Operator


Coding Example

Overloading Binary Operator


Coding Example

You might also like