I know how sizeof
works for calculating size of structures containing only data members. 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 on using sizeof
function will it also return the size of variables declared inside function AddInt
or will it only consider member variables (c
and d
)?
sizeof is to calculate the occupied memory size for the instance of that type. For struct/class instances, the function won't occupy extra memory (stored in text segment) for each instance while the data members of each instance will be different and need independent memory (stored in rw data segment).
The code part of functions (including variables within those functions) are never counted as part of the size of any data item.
If the structure has virtual functions, then that may add to the size of the structure.
The compiler is also free to add padding between data elements to support proper alignment of the members in a data structure.
In other words, sizeof
may produce a size greater than the individual elements. But any member functions will not be accounted into that size.
It will consider only member variables.
Furthermore, non-virtual member functions do not contribute to the size of struct
since they do not requite any run-time support.
To understand why it is so, imagine that from the compiler point of view this code is very similar to this pseudocode:
struct MyAdd
{
int c;
int d;
};
int MyAdd_AddInt(MyAdd* this)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With