You cannot obtain the size of a member-function, but you can obtain the sizeof a pointer-to-member-function:
int size = sizeof( &MyClass::foo );
The same goes for non-member functions (and static member functions), the size of the function cannot be obtained. It might be misleading because in most contexts, the name of the function decays automatically into a pointer to the function basically in the same way that an array decays to a pointer to the first element, but as in the case of arrays, sizeof
does not trigger the decay and that in turn means that you have to ask for the pointer explicitly.
First off, a virtual function is not a pointer with 8 bytes. In C++ nothing but sizeof(char)
is guaranteed to be any number of bytes.
Second, only the first virtual function in a class increases its size (compiler-dependent, but on most - if not all - it's like this). All subsequent methods do not. Non-virtual functions do not affect the class's size.
This happens because a class instance doesn't hold pointers to methods themselves, but to a virtual function table, which is one per class.
So if you had:
class A
{
virtual void foo();
}
and
class B
{
virtual void goo();
virtual void test();
static void m();
void x();
}
you would have sizeof(A) == sizeof(B)
.
And now:
Why siszeof(A) is 1 and sizeof(C) is 1 too ?
A
and C
have size 1 just because it's not allowed for a class to be of size 0. The functions have nothing to do with it. It's just a dummy byte.
Why siszeof(H) is 16 but sizeof(G) is 4 ?
G
has only one member that accounts for memory - the int
. And on your platform, sizeof(int) == 4
. H
, besides the int
, also has a pointer to the vftable
(virtual function table, see above). The size of this, size of int and allignment are compiler specific.
Why siszeof(E) is 16 but sizeof(F) is 4 ?
Explained above - non virtual methods don't take up memory in the class.
Why siszeof(D) is 8 but sizeof(E) is 16 ?
D
only contains the vftable
pointer which is apparently 8 bytes on your platform. E
also has an int, and the vftable
is aligned to 8 bytes. So it's something like:
class E
4 bytes for int | 4 padding bytes | 8 bytes for vftable pointer |
| x | x | x | x | | | | | v | v | v | v | v | v | v | v |
Best Answer
size
is actually C++17 functionality. The real benefit to is akin to the benefit ofbegin
andend
from C++11.Note that the first definition of
size
simply returns the container's size method.So if I have a templated function like this:
This could only be used with containers, but if I change that to:
It can be used with C-style arrays too. I've added a live example here: http://melpon.org/wandbox/permlink/Rlpi5wueA14JOW2P
In summary, you should always use
size
and other range based functions because of the improvements to generality and container agnostic code (see here for more).