Function Overloading


One neat thing you can do in C++ is declare two different functions that have the same name. How can this be? By passing different variables, C++ can tell that you want to use one versus another. This might let you make a function that can handle both strings and numbers; just write separate functions with the same name for each type of variable.

Sound neat? Well, let's try it out:

#include <iostream.h>

void burrito(int nacho)
{
  cout << "You sent an int!" << endl;
}

void burrito(char foo)
{
  cout << "You sent a char!" << endl;
}

void main(void)
{
  burrito(42);
  burrito('A');
  burrito(452.2);
}

Neat, huh? The first time you call the function burrito, it sees that you're passing an int, so it calls the one that was declared to have an int, and the second time, it sees you're passing a char, so it uses the one that declared a char. But what happens the third time? Unfortunately, since it can't decide to use the one that uses int versus the one that uses char, it won't work. The solution is to cast the call to a function to a type you know has a function defined for it. For instance, we'd change the third line to say:

burrito((int)452.2);

Which would convert the number 452.2 to an int, thereby making it choose the one that uses int as its parameter. This is similar to how you could change things into integers in Pascal by saying:

integer(52.1);

Which would return 52.


Table of Contents

Procedures/Functions | Returning Values | Passing Variables | Using Functions
Function Overloading | Default Parameters | Exercises