Article ID: 94579 - Last Review: December 11, 2003 - Revision: 2.0 INFO: Creating a Function Pointer to a C++ Member FunctionThis article was previously published under Q94579 On This PageSUMMARY
The text below describes generating a function pointer to a class member
function in code compiled with Microsoft C/C++ version 7.0 or later. The
declaration of a pointer to a class member function must include the class
name. However, the class name is omitted from the declaration of a pointer
to a static member function.
MORE INFORMATION
In the C and C++ languages, an application can define a variable that
contains the address of a function. You can call the function using this
variable instead of through the function name. In C++, a pointer to a
nonstatic member function contains the address of the function in the
class, not in the object. To call the function, use the appropriate member
selection operator (. or ->), the indirection operator (*), and the name of
an object of the class.
In most cases in the C language, function pointer declarations take the following form: int (*ptr)(); int (Sample::*ptr)(); The different ways to interpret the empty parentheses in function declarations is a major difference between the C and C++ languages. In C, a function pointer declaration that has no arguments is syntactically identical to the following: int (*ptr)(...); int (Sample::*ptr)(void); int (Sample::*ptr2)(int, int); To determine the procedure address to assign to a pointer variable, use the class name and the scope resolution operator (::). This syntax provides flexibility because a declared variable can contain the address of any object of the class. The object name in the function call determines the copy of the function used. The sample code below demonstrates declaring and using pointers to a class member function and to a static member function. Note that when the arguments in the function pointer declaration do not match the arguments of the function assigned to the pointer, the compiler generates errors C2440 and C2564. For example, if the "int" declaration is omitted from the argument list declaration for the function pointer, the compiler generates the following error messages: 16-bit
error C2440: 'initializing' : cannot convert from 'void (__far __pascal
Data::*)(int )__near ' to 'void (__far __pascal Data::*)(void )__near'
error C2564: formal/actual parameters mismatch in call through pointer to function 32-bit
error C2440: 'initializing' : cannot convert from 'void (Data::*)(int)
to 'void (Data::*)(void)" error C2197: 'void (Data::*)(void)' : too many actual parameters Sample Code79845
(http://support.microsoft.com/kb/79845/EN-US/
)
INFO: Old Style (K&R) Declarations Are Not Supported in C++
APPLIES TO
| Article Translations
|

Back to the top
