Function Pointers, part 2
(Page 1 of 4 )
In the previous article, Jun Nakamura introduced you to the use of regular function pointers, but when you write C++ code, you will be interested in C++ class member function pointers too. It is time to look at how to declare pointers to the members of classes you write for your applications.
Class Member Function Pointer Syntax
The declaration of a C++ member function pointer is a bit trickier than the regular ones we have seen so far and I have to say they look pretty strange as well.
You might wonder what the use of a member function pointer is. One of the uses I have found for it is in a protocol definition I wrote for a server application. The protocol is described in a static struct, where string messages are tied to pointers to the member functions in the protocol class that can handle specific messages. This ties the abstract knowledge of the messages to the lower functionality in the protocol class. Here is a section of that code:
static struct RQRSTable {
unsigned int privileges;
ProtocolImpl::RQType requestType;
HandleFunc function;
string header;
} rqrsTable[] =
{
// LOGIN -------------------------------------------------
// (CLT)RQ::LOGIN::<`username(str)`>
// example RQ::LOGIN::`Jun`
{
Read | Write | Admin, // privileges
ProtocolImpl::Request, // request type
&ProtocolImpl::login, // function
“CLT::RS::LOGIN” // header
},
...
};
By now you should be able to see that &ProtocolImpl::login is the function pointer stored in this struct. It describes which function has to be called for which header. A simple loop in a parser function can extrapolate the header from a message, look it up in the struct and execute the attached function by making a call to
rqrsTable[idx].function().
Next: Defining and Using C Member Function Pointers >>
More C++ Articles
More By J. Nakamura