Isn’t a pointer just an address? Or I’m missing something?
I tested with several types of pointers:
- pointers to any variables is the same (8B on my platform)
- pointers to functions are the same size, as pointers to variables (8B again)
- pointers to functions with different parameters – still the same (8B)
BUT pointers to member functions are bigger – 16B on my platform.
Three things:
- Why are pointers to member functions bigger? What more information do they need?
- As far as I know, the standard says nothing about the size of a pointer, except that
void*must be able to “contain” any pointer type. In other words, any pointer must be able to be casted tovoid*, right? If so, then whysizeof( void* )is 8, whilesizeofa pointer to member function is 16? - Are there any other examples for pointers, that are with different size (I mean, for standard platforms, not some rare and special ones)?
In the most normal situation, you can pretty much think of
as
(Starting to look like
C, right?) So you would think the pointer&A::foowould just be the same as a normal function pointer. But there are a couple of complications: Multiple inheritance, and virtual functions.So imagine we have:
It might be laid out like this:
As you can see, if you want to point to the object with an
A*or aC*, you point to the start, but if you want to point to it with aB*you have to point somewhere in the middle.So if
Cinherits some member function fromBand you want to point to it then call the function on aC*, it needs to know to shuffle thethispointer. That information needs to be stored somewhere. So it gets lumped in with the function pointer.Now for every class that has
virtualfunctions, the compiler creates a list of them called a virtual table. It then adds an extra pointer to this table to the class (vptr). So for this class structure:The compiler might end up making it like this:

So a member function pointer to a virtual function actually needs to be an index into the virtual table.
So a member function pointer actually needs 1) possibly a function pointer, 2) possibly an adjustment of the
thispointer, and 3) possibly a vtable index. To be consistent, every member function pointer needs to be capable of all of these. So that’s8bytes for the pointer,4bytes for the adjustment,4bytes for the index, for16bytes total.I believe this is something that actually varies a lot between compilers, and there are a lot of possible optimizations. Probably none actually implements it the way I’ve described.
For a lot of detail, see this (scroll to "Implementations of Member Function Pointers").