Thursday, July 24, 2008

OVERLOADING.

One of the many strengths of C++ is the ability to overload functions and operators. By overloading, the same function name or operator symbol can be given several different definitions. The number and types of the arguments supplied to a function or operator tell the compiler which definition to use. Overloading is most often used to provide different definitions for member functions of a class. But overloading can also be used for functions that are not a member of any class.

Suppose we need to search different types of arrays for a certain value. We can provide implementations for searching arrays of integers, floats, and doubles:

int Search (
const int* data,
const int key);

int Search (
const float* data,
const float key);

int Search (
const double* data,
const double key);

The compiler will ensure that the correct function is called based on the types of the arguments passed to Search(). When arguments do not exactly match the formal parameter types, the compiler will perform implicit type conversions (e.g., int to float) in an attempt to find a match.

Overloading is most often used for member functions and operators of classes. Most classes have overloaded constructors, for there is often more than one way to create a given object. All of the built-in types also have operators such as addition, subtraction, multiplication, and division. In fact, we can mix different types and still add them together:

int i = 1;
char c = 'a';
float f = -1.0;
double d = 100.0;
int result = i + c + f + d;

The compiler takes applies the type conversions appropriate for the above calculation. When we define our own types, we can inform the compiler which operations and type conversions can be applied to our type. The compiler will allow our type to blend in with the built-in types. We will see more examples of this when we look at classes in detail.

No comments: