Wednesday, May 5, 2010

Function overloading

C++ allows you to define several different functions with the same name, providing their parameter list differs. Here's a small example of doing so:
#include
void print(const char* string)
{
cout << "print(\"" << string << "\")" << endl;
}
void print(int i)
{
cout << "print(" << i << ")" << endl;
}
int main(void)
{
print("string printing"); // calls print(const char*)
print(5); // calls print(int)
return 0;
}
Compiling and running yields:
[d:\cppintro\lesson1]icc /Q+ funcover.cpp
[d:\cppintro\lesson1]funcover.exe
print("string printing")
print(5)
Handled right, this can severely reduce the number of names you have to remember. To do something similar in C, you'd have to give the functions different names, like "print_int" and "print_string". Of course, handled wrong, it can cause a mess. Only overload functions when they actually do the same things. In this case, printing their parameters. Had the functions been doing different things, you would soon forget which of them did what. Function overloading is powerful, and it will be used a lot throughout this course, but everything with power is dangerous, so be careful.
To differentiate between overloaded function the parameter list is often included when mentioning their name. In the example above, I'd say we have the two functions "print(int)" and "print(const char*)", and not just two functions called "print." [Compilers will generally do something similar when reporting error messages as well, so if you have used function overloading in your program look closely at which of the functions the compiler is concerned about

No comments:

Post a Comment