Operatoroverloading
Operatoroverloading
Operator Overloading
• C++ has the ability to provide the operators with the
special meaning for a data type.
• The mechanism of giving such special meanings to an
operator is known as Operator overloading.
• It provides a flexible option for creation of new
definitions for most of C++ operators.
• Operator Overloading is a specific case of
polymorphism in which some or all of operators like +,
=, or == have different implementations depending on
the types of their arguments.
• if a,b and c are variables(objects) of user defined data
type(class) then the statement c=a+b; will not work as
complier do not know how to add two variables(objects) of
user defined data type(class). Error will be generated.
• In order to make this operation possible we need to overload
the + operator by making a function to perform the desired
task.
• This property of giving additional meaning to the existing
operators so that they can work with variables of user
defined data type is called operator overloading.
• Providing additional meaning to an existing operator does not
change the original meaning of operator but it simply extends
the functionality of operator.
Operator Overloading
• Unary operator
• Binary operator
Operator invocation
• Unary operator
• Binary operator
Operators Member Functions Non Member
Functions (Friend
Function)
{
#include<conio.h>
//clrscr();
using namespace std;
score s1,s2; // object definition
class score
cout<<"\n initial value of s1 object = "<<s1.show();
{
cout<<"\n initial value of s2 object = "<<s2.show();
private: int val;
++s1; //operator function call
public: score()
++s1; // same as s1.operator++();
{ val=0;} ++s2;
void operator++() //operator cout<<"\n final value of s1 object = "<<s1.show();
function definition
cout<<"\n final value of s2 object = "<<s2.show();
{ val= val+1; }
getch();
int show()
return 0;
{ return (val); }
}
};
Binary Operators