Saturday, 20 April 2013

Overloading of Functions and Operators

Several different functions can be given the same name. C++ will choose one of the
functions at compile time , given the type and number
of parameters in the function call.

The following print functions print an int, a string and an array of int:

#include <stdio.h>
#include <string.h>
void print(int i)
// print an integer
{
printf("%d\n", i);
}
void print(char *str)
// print a string
{
printf("%s\n", str);
}
void print(int a[], int elem)
// print an array of integers
{
for (int i = 0; i < elem; i++) printf("%d\n", a[i]);
}
int main()
{
int i = 6;
char *str = "hello";
int vals[] = { 1, 2, 3, 4 };
print(i); // call print(int)
print(str); // call print(char *)
print(vals,sizeof(vals)/sizeof(int));
// call print(int [], int)
return 0;
}
It should be noted that there are better ways of handling printing of user defined types in
C++.

No comments:

Post a Comment