5.1.  Function Declarations

[ fromfile: functions.xml id: prototypes ]

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 them here. Every function has:

  1. A name

  2. A return type (which may be void)

  3. A parameter list (which may be empty)

  4. A body (a group of statements)

The first three are the function's interface, and the last is its 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:

Here are a few prototypes.

int toCelsius(int fahrenheitValue);
QString toString();
int main(int argc, char* argv[]);

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

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 naming the parameters the problem is eliminated and the function has documented itself.