EECE 230 – Lectures Notes: S. Karaki
47
8
Operator Overloading
8.1 Introduction
In function overloading more than one function definition may share the same name. The
compiler recognizes the required function by argument type matching. Function
overloading forms the foundation of operator overloading.
Assume a class complex:
class complex
{
private:
double real, imag;
public:
complex(double r, double i = 0.0)
{
real = r;
imag = i;}
friend complex sqrt(complex);
};
complex sqrt(const complex c)
{
…
}
With such definition, it is now possible to evaluate the square root of a complex number
as follows:
double d = 9;
double t = sqrt(d)
complex c(3.0, 4.0);
complex z = sqrt(c);
Exercise:
Implement function complex sqrt to calculate the square root of a complex
number.
8.2 Fundamentals of Operator Overloading
C++ allows (most) operators to be overloaded, i.e. to be given mew meanings. Note that
one cannot redefine the associativity and arity of an operator, and one cannot also define
new operators!

This
** preview**
has intentionally

**sections.**

*blurred***to view the full version.**

*Sign up*