The header common.h
forward declares a class Test
and a function receiving a member function pointer:
class Test;
void func(const Test &t, int (Test::*f)() const, int x, int y);
In the source file target.cpp
, I define the function such that
#include "common.h"
void func(const Test &t, int (Test::*f)() const, int x, int y) {
std::cout << "f: " << (t.*f)() << ", x: " << x << ", y: " << y << std::endl;
}
In my main file, I define the class Test
and use the function func
:
class Test {
public:
int example() const { return 1; }
};
#include "common.h"
int main() {
Test t;
func(t, &Test::example, 0xaaaaaaaa, 0xbbbbbbbb);
return 0;
}
Obviously this is a bit smelly since pointers to member functions are sometimes more than a simple pointer. But the resulting behavior is a bit overwhelming: The given parameters 0xaaaaaaaa
and 0xbbbbbbbb
won't be passed correctly to the function. Or to be more precise, the function func
interprets the given stack differently than the data is pushed on the stack by the caller. The size of f
depends on whether the class is only forward declared or actually defined. The output compiled with Visual Studio 2013 is:
f: 1, x: 0, y: 2130567168
I thought, if a forward declaration is sufficient, it really doesn't matter whether there's a definition given or not.
Function pointer to member function in C++ In C++ , function pointers when dealing with member functions of classes or structs, it is invoked using an object pointer or a this call. We can only call members of that class (or derivatives) using a pointer of that type as they are type safe.
Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). Example: // Forward Declaration of the sum() void sum(int, int); // Usage of the sum void sum(int a, int b) { // Body }
Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object.
In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.
By default, MSVC favours speed over correctness with pointers to member. You can force it to work according to the standard by passing the compiler flag /vmg
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With