< Previous | Contents | Next >

Creating Overloaded Functions

To create an overloaded function, you simply need to write multiple function definitions with the same name and different parameter lists. In the Triple program, I write two definitions for the function triple(), each of which specifies a different type as its single argument. Here are the function prototypes:

int triple(int number); string triple(string text);

The first takes an int argument and returns an int. The second takes a string

object and returns a string object.

In each function definition, you can see that I return triple the value sent. In the first function, I return the int sent, tripled. In the second function, I return the string sent, repeated three times.


Tra p

image

To implement function overloading, you need to write multiple definitions for the same function with different parameter lists. Notice that I didn’t mention anything about return types. That’s because if you write two function definitions in which only the return type is different, you’ll generate a compile error. For example, you cannot have both of the following prototypes in a program:

int Bonus(int); float Bonus(int);

image

Inlining Functions 177