Sams Teach Yourself C++ in 21 Days

(singke) #1
On line 10,typedefis used to declare VPFto be of the type “pointer to function
that returns voidand takes two parameters, both integer references.”
On line 11, the function PrintVals()is declared to take three parameters: a VPFand two
integer references. On line 19,pFuncis now declared to be of type VPF.
After the type VPFis defined, all subsequent uses to declare pFuncand PrintVals()are
much cleaner. As you can see, the output is identical. Remember, a typedefprimarily
does a replacement. In this case, using the typedefmakes your code much easier to
follow.

Pointers to Member Functions ............................................................................


Up until this point, all the function pointers you’ve created have been for general, non-
class functions. It is also possible to create pointers to functions that are members of
classes. This is a highly advanced and infrequently used technique that should be avoided
whenever possible. It is, however, important to understand this technique as some people
do choose to use it.
To create a pointer to member function, use the same syntax as with a pointer to func-
tion, but include the class name and the scoping operator (::). Thus, if pFuncpoints to a
member function of the class Shape, which takes two integers and returns void, the dec-
laration for pFuncis the following:
void (Shape::*pFunc) (int, int);
Pointers to member functions are used in the same way as pointers to functions, except
that they require an object of the correct class on which to invoke them. Listing 15.10
illustrates the use of pointers to member functions.

LISTING15.10 Pointers to Member Functions
0: //Listing 15.10 Pointers to member functions using virtual methods
1:
2: #include <iostream>
3: using namespace std;
4:
5: class Mammal
6: {
7: public:
8: Mammal():itsAge(1) { }
9: virtual ~Mammal() { }
10: virtual void Speak() const = 0;
11: virtual void Move() const = 0;
12: protected:

528 Day 15


ANALYSIS
Free download pdf