You can not only add two user defined data types but also perform various operations by using operator overloading
.
The general syntax for operator overloading is as follows:
If you want to add two objects such as:
eg: objres=obj1+obj2;//belong to class s
The operation obj1+obj2
should return an object of the same user defined data type.
So, the return type of your overloaded function should be s
.
s operator+(s obj)
{
s temp;
temp.datamember=datamember+obj.datamember;//perform operation on datamembers
return temp;//return object to objres
}
This will return an object with specific operation performed on it.
It should be noted that operator
is a keyword in C++ and it's general ethics to not to change the meaning if the operator being overloaded.Also if an operator is unary it remains unary and if an operator is binary it remains binary and requires one and two operands respectively.
Similarly, operators like *,>,<,==,/,++,--
can be overloaded as well.