06 Overloading
06 Overloading
There are many operators available that work on built-in types, like int or
double (+, -, *, /, ==, !=, <<, >>).
We could imagine these operators being implemented by function calls
made automatically by c++,
For example:
int x = 1 + 2;
Could automatically be replaced by a function call that looks like:
int x = operator+(1, 2)
With the following prototype:
int operator+(int p1, int p2); /* returns sum of p1 and p2 */
Rethinking Operators, cont.
Another example:
double var = 1.1;
double x = 4.3 * 2.1 - var ;
Could automatically be replaced by function calls that look like:
double x = operator-(operator*(4.3, 2.1), var)
With the following prototypes:
double operator*(double p1, double p2); /* returns product of p1 and p2 */
double operator-(double p1, double p2); /* returns difference of p1 and p2 */
Example 1:
Consider the following use of arithmetic operators:
Now consider if we wanted to add fraction objects in this familiar way (this is
pseudo-code):
– It should be clear that this would not make sense to the compiler by default. Fraction is a
programmer-defined type. How would the computer know about common denominators, etc?
– These code statements would be nice to use, however, because it's the same way we use other
numeric types (like int and double).
Motivation, cont.
Example 2:
Consider screen output, we know the following is legal:
– Again, it is clear the compiler has no idea how a Fraction object should be output to the screen.
Example:
The string class has overloaded operator<< to allow output of strings using cout.
The compiler will call this function automatically when we use the << operator
or we can call it explicitly.
See example1.cpp.
Operator Overloading Details
Lets see how we could add fractions using the '+' operator by creating a
member function.
What we are shooting for:
Fraction f1, f2(1, 2), f3(3, 4);
f1 = f2 + f3;
The second line translates to:
f1 = f2.operator+(f3); /* member overload */
OR
f1 = operator+(f2, f3); /* stand-alone overload */
Overloading Arithmetic Operators, cont.
The stream insertion (<<) and extraction (>>) operators will not
automatically work with your class (should be obvious by now).
Since we know the stream insertion operator is overloaded for the string
class, here is what the overload prototype is:
ostream& operator<<(ostream &os, const string& s);
Here are the function prototypes for overloading the insertion and extraction
operators for the Fraction class:
ostream& operator<<(ostream &os, const Fraction &f);
istream& operator>>(istream &is, const Fraction &f);