Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size Of Structures With Functions In C++

Tags:

c++

sizeof

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)?

like image 924
chetan Avatar asked Aug 22 '13 12:08

chetan


3 Answers

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).

like image 104
JackyZhu Avatar answered Oct 05 '22 23:10

JackyZhu


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.

like image 25
Mats Petersson Avatar answered Oct 06 '22 00:10

Mats Petersson


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)
{
   ...
}
like image 37
Sergey K. Avatar answered Oct 06 '22 01:10

Sergey K.