Rules for Overloading Operators
- Only existing operators can be overloaded. New operators cannot be created.
- The overloaded operator must have at least one operand that is of user defined type.
- The basic meaning of an operator cannot be changed. That is the plus operator cannot be used to subtract one value from the other.
- Overloaded operator follow the syntax rules of the original operators. They cannot be overridden.
- There are some operators that cannot be overloaded. They are Size of, . ,: :,?:.
- Friend function cannot be used to overload certain operators ( = ,( ) ,[ ] ,->).However member functions can be used to overload them.
- Unary operators, overload by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument.
- Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments.
- When using binary operator overloaded through a member function, the left hand operand must be an object of the relevant class.
- Binary arithmetic operators such as +,-,*,and / must explicitly return a value. They must not attempt to change their own arguments.
Example
#include <iostream.h>
#include <string.h>
class Product{
public:
Product() : name(NULL) {}
Product(char* str);
const Product& operator=(const Product& );
void Print() { cout << "Product: " << name << endl; }
const char* getProduct() const { return name; }
private:
char * name;
};
Product :: Product(char* str){
name = new char[strlen (str)+1];
strcpy (name, str);
}
const Product& Product :: operator=(const Product& p){
delete [] name;
name = new char[strlen(p.getProduct())+1];
strcpy(name, p.getProduct());
return *this; // This will allow assignments to be chained
}
int main(){
Product p1("Hammer"), p2("Shovel"), p3;
p3 = p2; // p2 and p3 will have equivalent name strings
p2.Print();
p3.Print();
p3 = p2 = p1; // p1, p2, and p3 will have equivalent name strings
p1.Print();
p2.Print();
p3.Print();
return 0;
} |