Size of structures with functions in C ++

I know how sizeof works to calculate the size of structures containing only data elements. But, for example, if I have the following structure in C ++

 struct MyAdd() { int AddInt() { int a=5; int b=5; return a+b; } int c; int d; }; 

So, using the sizeof function, will it also return the size of the variables declared inside the AddInt function, or will it only consider member variables ( c and d )?

+7
c ++ sizeof
source share
3 answers

It will only consider member variables.

In addition, non-virtual member functions do not contribute to the size of the struct , since they do not require runtime support.

To understand why this is so, imagine that from the point of view of the compiler, this code is very similar to this pseudocode:

 struct MyAdd { int c; int d; }; int MyAdd_AddInt(MyAdd* this) { ... } 
+18
source share

The code part of functions (including variables in these functions) is never taken into account as part of the size of any data element.

If the structure has virtual functions, this can add to the size of the structure.

The compiler can also add padding between data items to support proper alignment of items in the data structure.

In other words, sizeof can create a size larger than individual elements. But any member functions will not be counted in this amount.

+2
source share

sizeof - calculate the size of the occupied memory for an instance of this type. For instances of struct / class, the function will not take up additional memory (stored in the text segment) for each instance, while the data members of each instance will be different and need independent memory (stored in the rw data segment).

+2
source share

All Articles