Operator Overloading
Here is a list of some common operators that you might overload, and how you would declare them. Note that some of the operators are member functions of a class, and others are friend functions.
class Foo
{
public:
Foo &operator= (const Foo &rhs);
Foo &operator+= (const Foo &rhs);
Foo &operator-= (const Foo &rhs);
Foo &operator/= (const Foo &rhs);
Foo &operator*= (const Foo &rhs);
bool operator< (const Foo &rhs) const;
bool operator<= (const Foo &rhs) const;
bool operator> (const Foo &rhs) const;
bool operator>= (const Foo &rhs) const;
bool operator== (const Foo &rhs) const;
bool operator!= (const Foo &rhs) const;
Foo &operator++ (); //
Used in ++x
Foo &operator++ (int); // Used in x++
Foo &operator-- (); //
Used in ++x
Foo &operator-- (int); // Used in x++
Foo operator+ (const Foo &rhs) const;
Foo operator- (const Foo &rhs) const;
Foo operator/ (const Foo &rhs) const;
Foo operator* (const Foo &rhs) const;
friend ostream &operator<< (ostream &out, const Foo
&value);
friend istream &operator>> (istream &in, Foo &value);
};
Other notes:
On some operators, you can use different parameters than the ones listed. For example, in order for C++ to understand the following code:
int x = 1;
Foo A;
A += x;
You would need to provide an operator+=. But instead of taking a parameter of Foo, this one would take a parameter of int.
Foo &operator+= (int rhs);
This would allow you to add ints to Foos.
Operator=
Here is an example operator=. Every operator= you write will have this same form:
Foo &Foo::operator= (const Foo &rhs)
{
if (this != &rhs)
{
// do whatever is necessary to make this
// object equal to rhs. Generally this
// means copying the values of data members
}
return *this;
}
Operator==
Here is an example operator==. Every operator== you write will have this same form:
int Foo::operator== (const Foo &rhs) const
{
// If this object is the same instance
// as rhs, then they are automatically
// equal, so return 1.
if (this == &rhs)
return 1;
// Otherwise, compare data members and
// return 1 if data members are equal,
// 0 if data members are not equal.
}
Operator+, Operator-, Operator/, Operator*
operator+, operator-, operator/, and operator* all return copies of a Foo instead of a reference to a Foo. This is important. Consider the following code:
void main ()
{
Foo x;
Foo y;
Foo z;x = y + z;
}
The compiler translates x = y + z into x.operator= (y.operator+ (z)). Should y actually be changed? If x, y, and z were ints, would you expect the value of y to change?
Inside these four operators, you need to make a copy of the current object and make changes to the copy. A skeleton operator+ might look like:
Foo Foo::operator+ (const Foo &rhs) const
{
Foo copy = *this;
// make changes to the copy
return copy;
}