Sams Teach Yourself C++ in 21 Days

(singke) #1
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 1
x: 1 y: 2
New value for ValOne: 2
New value for ValTwo: 3
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 3
x: 2 y: 3
x: 8 y: 27
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 2
x: 8 y: 27
x: 64 y: 729
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 4
x: 64 y: 729
x: 729 y: 64
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 0
It was tempting to put PrintVals()at the top of the whileloop and again at the
bottom, rather than in each casestatement. This would have called PrintVals()
even for the exit case, however, and that was not part of the specification.
Setting aside the increased size of the code and the repeated calls to do the same thing,
the overall clarity is somewhat diminished. This is an artificial case, however, created to
show how pointers to functions work. In real-world conditions, the advantages are even
clearer: Pointers to functions can eliminate duplicate code, clarify a program, and enable
tables of functions that can be called based on runtime conditions.

OUTPUT


520 Day 15


ANALYSIS

Object-oriented programming should generally allow you to avoid the need
to create or pass pointers to functions. Instead, call the desired function on
the desired object or the desired static member function on the class. If you
need an array of function pointers, ask yourself whether what you really
need is an array of appropriate objects.

TIP

Shorthand Invocation
The pointer to function does not need to be dereferenced, although you are free to do
so. Therefore, if pFuncis a pointer to a function taking an integer and returning a vari-
able of type long, and you assign pFuncto a matching function, you can invoke that
function with either
pFunc(x);
or
(*pFunc)(x);
The two forms are identical. The former is just a shorthand version of the latter.
Free download pdf