Function Declarations
Functions in C++ are very similar to functions and subroutines in other languages. C++ functions, however, support many features that are not found in some languages, so it is worthwhile discussing each of them here. Each function has:
- A name
- A return type (which may be void)
- A parameter list (which may be empty)
- A body (a group of statements)
The first three are the function's interface, and the last is the implementation.
A function must be declared before it is used for the first time. The mechanism for declaring a function is called a function prototype. A function prototype is a declaration that must include
- The function's return type
- The function's name
- An ordered, comma separated list of the types of the function's parameters
Here are a few prototypes.
int toCelsius(int fahrenheitValue); QString toString(); int main(int argc, char* argv[]);
Even though parameter names are optional in function prototypes, it is good programming practice to use them. They constitute a very effective and efficient part of the documentation for a program. Furthermore, many documentation generators (e.g., kdoc) require them.
A simple example can help to show why parameter names should be used in function prototypes. Suppose we needed a constructor for a Date class that we designed and we wanted that constructor to initialize the Date with values for the year, month, and day. If we presented the prototype as Date(int, int, int), the user of that class would not know immediately what order to list the three values when constructing a Date object. Since several of the possible orderings are in common use somewhere on the planet, there is no "obvious" answer that would eliminate the need for more information. By simply naming the parameters the problem is eliminated and the function has documented itself.
In multi-file applications, function prototypes are usually stored in header files.