operator overloading in c++

Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type.


Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

Almost any operator can be overloaded in C++. However there are few operator which can not be overloaded. Operator that are not overloaded are follows
– scope operator – ::
– sizeof
– member selector – .
– member pointer selector – *
– ternary operator – ?:

Syntax
Return_type class_name :: operator operator_symbol(argument_list)
{
//function body
}


here operator is keyword and operator_symbol is operator to be overloaded.

Implementing Operator Overloading
Operator overloading can be done by implementing a function which can be :
Member Function
Non-Member Function
Friend Function

Operator overloading function can be a member function if the Left operand is an Object of that class, but if the Left operand is different, then Operator overloading function must be a non-member function.
Operator overloading function can be made friend function if it needs access to the private and protected members of class.

Restrictions on Operator Overloading
Following are some restrictions to be kept in mind while implementing operator overloading.

– Precedence and Associativity of an operator cannot be changed.
– Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains binary etc.
– No new operators can be created, only existing operators can be overloaded.
– Cannot redefine the meaning of a procedure. You cannot change how integers are added.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s