» Function Overloading by Travis Dane |
|
(Login to remove green text ads)
It's recommended to understand what's in the Intro to
Functions tutorial before reading this tutorial.
Sometimes it might occur that you have 2 functions that have the same name but each do something else. If the two functions
accept different type of arguments passed in you can apply something called Function Overloading. With Function Overloading
the compiler determines what function you're calling for by checking it's name AND the type of arguments passed in.
A example of Function Overloading in action.
Code:
#include <iostream> // Include the newest input-output stream header
#include <conio.h>
using namespace std; // So we won't have to specify this namespace to use it's functions
void PrintaNumber(int number) // Our first function
{
cout << number;
}
void PrintaNumber(float number) // Our second Function
{
cout << number;
}
/*
Oh oh, The functions have the same name! No worries though,
The type of number that is passed in differs in the second
function and so the compiler can distinguise the two functions.
*/
int main(void) // The program's entry point
{
int number=4; // A integer that we're going to pass to the function that handles an integer number
float pi=3.14159265f; /* A float that we're going to pass to the function that handles a float number,
Notice the "f" i put behind the number? I put it there to make sure the compiler
knows it's a float, Even though i specified it to be a float, Float's have a very
big precision behind the comma, And if it has only a few numbers behind it it's going
to complain about it, So we'll solve it like this.
*/
// Here we're going to test the two functions
PrintaNumber(number);
cout << "+";
PrintaNumber(pi);
cout << "=" << number+pi << endl;
getch(); // Prevent the program from exiting premature
return 0; // Return succes
}
See how easy it actually is? This code is compiled and tested with VC++ .NET but should be backwards compatible with all
of the VC++ version's.
Well, So much for this tutorial, If you experience any problems with the code tell me.
|
|