Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    cpp
  » Function Overloading
      by Travis Dane
 Page 1 of 1 
   

(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.




 
 Page 1 of 1 
   

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2008, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting