Home > Uncategorized > Random Information: C++ Function Pointer Syntax

Random Information: C++ Function Pointer Syntax

February 20th, 2009

C++ pointer syntax is many things, but is not pretty. It is so un-pretty that, around the office, I have somehow wound up the local expert in the field of typing them out.

The syntax is really arbitrary and complicated, but, if you strip it down, it’s pretty basic.

Non-class-method pointers are pretty familiar. They come up all the time in C, and they look like this:

ReturnType (CALLING_CONVENTION *NAME)(Arg, Arg, ...)

CALLING_CONVENTION is going to be something like __stdcall, __cdecl, __fastcall, or whatever. It is optional.
The “NAME” bit is the confusing part. That’s where the name of the type or the variable goes. For instance:

// declare a variable named 'ptr', that points to a
// function that takes an int, and returns an int
int (*ptr)(int);

// Make a typedef for a pointer to a function that takes no arguments,
// and returns a double
typedef double (*DoubleFunction)();

Pointer-to-method

These are almost the same, but you have a class name and a ::

// A variable named 'ptr' that is a method of type T,
// takes no arguments, and returns void
void (T::*ptr)();

// Declare a typedef for a method on the IDirect3D8 interface.
// (all COM methods use the __stdcall calling convention)
typedef HRESULT (__stdcall IDirect3D8::*D3D8Function)();

That’s about all the useful information there is to have about typing out function pointers that do various things. Just for kicks, let’s dive into insanity:

Function References

There is also a such a thing as a function reference. They’re just like other kinds of C++ references. ex:

void call_a_function_reference(void (__cdecl &this_is_the_parameter_name)(int)) {
    this_is_the_parameter_name(0);
}

const

oh god what the hell is going on here

void try_to_clobber_a_const_function_pointer(void (* const parameter_name)()) {
    parameter_name = 0; // illegal because this parameter is const
}

Uncategorized

Comments are closed.