Question

I'm trying to make some callbacks from member functions and everything was ok until I tried to use a template class derived from 2 classes as callback object when I got the following error:

error C2440: 'reinterpret_cast' : Pointers to members have different representations; cannot cast between them

This thing signaled me that member function pointers have different representations(doh!)

What are these representations? What is the difference between them?

Was it helpful?

Solution

Danny Kalev explains this quite nicely:

The Underlying Representation of Pointers to Members

Although pointers to members behave like ordinary pointers, behind the scenes their representation is quite different. In fact, a pointer to member usually consists of a struct containing up to four fields in certain cases. This is because pointers to members have to support not only ordinary member functions, but also virtual member functions, member functions of objects that have multiple base classes, and member functions of virtual base classes. Thus, the simplest member function can be represented as a set of two pointers: one holding the physical memory address of the member function, and a second pointer that holds the this pointer. However, in cases like a virtual member function, multiple inheritance and virtual inheritance, the pointer to member must store additional information. Therefore, you can't cast pointers to members to ordinary pointers nor can you safely cast between pointers to members of different types.

To get a notion of how your compiler represents pointers to members, use the sizeof operator. In the following example, the sizes of a pointer to data member and a pointer to a member function are taken. As you can see, they have different sizes, hence, different representations:

struct A
{
 int x;
 void f();
};
int A::*pmi = &A::x;
void (A::*pmf)() = &A::f;
int n = sizeof (pmi); // 8 byte with my compiler
int m = sizeof (pmf); // 12 bytes with my compiler

Note that each of these pointers may have a different representation, depending on the class in question and whether the member function is virtual.

OTHER TIPS

This is a Microsoft thing: they make pointers to member functions smaller in some cases, at the cost of producing pointers to member functions that have different representations, as you've just seen. There's a switch to turn this off (/vmg), so that all pointers to members have the same representation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top