C++ sizeof() Operator – How to Apply to Non-Static Class Member Methods

c++member-functionssizeof

struct MyClass {
  int foo () { return 0; }
};

unsigned int size = sizeof(MyClass::foo);  // obviously error

Can we apply sizeof() to member methods from outside the class ? Do we need to declare object to get it ?

Edit: I know that above code will give error (that's why word 'obviously'). Wanted to know if we can at all apply the sizeof() to a member method. I don't want to describe the use case for that in length.

Best Answer

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.

Related Question