C++: Pointers to member functions

This is quite an advanced C++ topic. In both plain C and C++ there are pointers to functions, which allow us to dynamically select the function to invoke from many which have the same signature. A typical example of this is defining a few comparison functions, all with the same signature, in order to dynamically select how to sort a collection (ascending, descending, alphabetically, etc).

C++ brings in a new concept over C: pointers to member functions. Most of the times, plain pointers to function are not very Object Oriented, since they are static and all. The C++ syntax for declaring pointers to member functions is similar to that of pointers to functions, we just have to specify the class:

// Generic syntax
// functionReturnType (ClassName::*nameOfPointerToMemberFunctionVariable)( functionArguments );

// Concrete example
LRESULT (CCoConsola3D::*onMouseWheelHandler) ( UINT, WPARAM, LPARAM, BOOL& );

The concrete example declares a variable called onMouseWheelHandler, which can point to any member function of the CCoConsola3D class which returns an LRESULT and receives an UINT, a WPARAM, and a BOOL&.

That's it for declaration, let's move on to definition/assignment:

/*
 * We assume that CCoConsola3D has a member function called
 * OnMouseWheelHandlerNotifyGUI which has a signature matching
 * that of onMouseWheelHandler
 */
onMouseWheelHandler = &CCoConsola3D::OnMouseWheelHandlerNotifyGUI;

Finally, in order to invoke the selected member function, we need an instance of CCoConsola3D and some ugly syntax:

// Parentheses are mandatory! Otherwise this won't compile

// ...In some other CCoConsola3D member function:
(this->*onMouseWheelHandler)(uMsg, wParam, lParam, bHandled);

// ...In a class which uses a CCoConsola3D object called console:
(console.*onMouseWheelHandler)(uMsg, wParam, lParam, bHandled);

Pointers to member functions offer many possibilities: there are some authors who consider it another form of polymorphism, since it allows us to dynamically change an object's behavior. If we compare it with the usual inheritance+virtual functions approach, it has the advantage of not needing to destroy and create an object in order to change its behavior. This can make pointers to member functions preferrable when creation and/or destruction are time/space expensive, which is actually the case with a CCoConsola3D.

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x