C++ Tutorial Home Page

C++ Operator Overloading

What is operator overloading
Rules for overloading Operators
Operator Overloading restrictions
List of operators that cannot be overloaded.
Overloading Unary operator
Overloading increment operator(++)
Overloading decrement operator(–)
Overloading unary operator(-)
Overloading increment operator(++) postfix
Overloading decrement operator(–) postfix
Overloading increment operator (++) with friend function
Overloading increment operator (–) with friend function
Increment the time using ++
Decrement the time using ++
Overloading Binary operator(+,-,*,/,%)
Add two object using “+” operator with friend function
Overloading “-” operator
Overloading “*” operator
Overloading “/” operator
Overloading “%” operator
overloading all (+,-,*,/,%)
Overloading “+” operator with friend function
class distance (feet,inches) with “+” operator
class distance (feet,inches) with “+” operator with friend function
class distance (km,m) with “+” operator
class distance (km,m) with “+” operator with friend function
class distance (m,cm) with “+” operator
class distance (m,cm) with “+” operator with friend function
class distance (km,m,cm) with “+” operator
class distance (km,m,cm) with “+” operator with friend function
class distance (km,m,cm,mm) with “+” operator
class distance (km,m,cm,mm) with “+” operator with friend function
class time(hh,mm,ss) with “+” operator
class time(hh,mm,ss) with “+” operator with friend function
class complex(real,ing) with “+” operator
class complex(real,ing) with “+” operator with friend function
class string(str) with “+” operator
class string(str) with “+” operator with friend function
overloading “+=” operator

C++:Operator Overloading

Operator overloading is an important feature of C++ and it allows to attach an additional meaning to operators when used with user defined data types i.e. classes. When an operator is overloaded, it gains an additional meaning relative to the class in which it is used.

or

Operator overloading refers to the technique of giving normal c++ operators an additional meaning when they are applied to user defined data types/classes.

Using operator overloading complex program segments can be replaced by more natural looking statements.

Example:

(1) To concatenate two string we write the statement as

string s1,s2,s3;
s3=s2.concatenate(s1);
s3=s2.hello(s1);
s3=hello(s1,s2);

Using operator overloading the above statement can be written as
s3=s1+s2;

(2) To add two distance objects

distance d1,d2,d3;
d1.read();d2.read();
d3=add(d1,d2);
d3=d1.add(d2);

d3=hello(d1,d2);
d3=d1.hello(d2);

Using operator overloading the above statements can be written as
d3=d1+d2;

Number Of Visitors

0238193