More about Program Structure
The important bits that you learned in this chapter include:
A pointer to a function stores the address of a function, plus information about the number and types of parameters and return type for a function.
You can use a pointer to a function to store the address of any function with the appropriate return type, and number and types of parameters.
You can use a pointer to a function to call the function at the address it contains. You can also pass a pointer to a function as a function argument.
An exception is a way of signaling an error in a program so that the error handling code can be separated from the code for normal operations.
You throw an exception with a statement that uses the keyword throw.
Code that may throw exceptions should be placed in a try block, and the code to handle a particular type of exception is placed in a catch block immediately following the try block. There can be several catch blocks following a try block, each catching a different type of exception.
Overloaded functions are functions with the same name, but with different parameter lists.
When you call an overloaded function, the function to be called is selected by the compiler based on the number and types of the arguments that you specify.
A function template is a recipe for generating overloaded functions automatically.
A function template has one or more arguments that are type variables. An instance of the function template — that is, a function definition — is created by the compiler for each function call that corresponds to a unique set of type arguments for the template.
You can force the compiler to create a particular instance from a function template by specifying the function you want in a prototype declaration.
You also got some experience of using several functions in a program by working through the calculator example. But remember that all the uses of functions up to now have been in the context of a traditional procedural approach to programming. When we come to look at object-oriented programming, you will still use functions extensively, but with a very different approach to program structure and to the design of a solution to a problem.
Exercises
You can download the source code for the examples in the book and the solutions to the following exercises from http://www.wrox.com.
1.Consider the following function:
int ascVal(size_t i, const char* p)
{
// print the ASCII value of the char if (!p || i > strlen(p))
return -1; else
return p[i];
}