Operator Overloading - Examples

Examples

In this case, the addition operator is overloaded to allow addition on a user-defined type "Time" (in C++):

Time operator+(const Time& lhs, const Time& rhs) { Time temp = lhs; temp.seconds += rhs.seconds; temp.minutes += temp.seconds / 60; temp.seconds %= 60; temp.minutes += rhs.minutes; temp.hours += temp.minutes / 60; temp.minutes %= 60; temp.hours += rhs.hours; return temp; }

Addition is a binary operation, which means it has left and right operands. In C++, the arguments being passed are the operands, and the temp object is the returned value.

The operation could also be defined as a class method, replacing lhs by the hidden this argument; however this forces the left operand to be of type Time and supposes this to be a potentially modifiable lvalue:

Time Time::operator+(const Time& rhs) const { const Time temp = *this; /* Copy 'this' which is not to be modified */ temp.seconds += rhs.seconds; temp.minutes += temp.seconds / 60; temp.seconds %= 60; temp.minutes += rhs.minutes; temp.hours += temp.minutes / 60; temp.minutes %= 60; temp.hours += rhs.hours; return temp; }

Note that a unary operator defined as a class method would receive no apparent argument (it only works from this):

bool Time::operator! const { return ((hours == 0) && (minutes == 0) && (seconds == 0)); }

Read more about this topic:  Operator Overloading

Famous quotes containing the word examples:

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)