Does the struct constructor take up space inside the structure space?

Most of the time I use struct

to store all the parameters for the socket data structure of the socket, and then I can easily copy, pass, or put the entire structure on the socket by simply passing in the starting address and its size.

If I add a constructor in struct

for the short array variable, will the constructor take up any space inside the structure? Or can I handle with the struct

constructor the same as struct

without the constructor and copy the whole thing struct

to the socket with its starting address and its size, and its space is still contiguously allocated?

+3


source to share


2 answers


No, no virtual member functions do not contribute to sizeof

your object. The existence of at least one virtual function is helpful (however, constructors cannot be virtual), since the compiler usually implements them with a pointer (vpointer) to an array of function pointers (vtable), so it must store that pointer (4 or 8 bytes usually) ...



+6


source


This question is related to the C ++ Object Model. Normal function does not increase data size. Also, if we add a virtual function, the compiler will generate a __vptr to point to the virtual function table, which will increase the data size of the structure.

For example, I have. C.

#include <iostream>
using namespace std;
struct X
{
    X(){}
    int i;
    int j;

};

int main()
{
    X x;
    cout << sizeof(x) << endl;
}

      

Here I am using my IBM XL C ++ compiler on my computer to compile and run it:

xlC -+ a.C
./a.out

      

The output will be 8, which will be the same as the struct, only int i and int j.



But if I add two virtual functions:

#include <iostream>
using namespace std;
struct X
{
    X(){}
    int i;
    int j;
    virtual void foo(){}
    virtual void bar(){}
};

int main()
{
    X x;
    cout << sizeof(x) << endl;
}

      

If you recompile and run it:

xlC -+ a.C
./a.out

      

The output will be 16.8 for two ints, 8 for __vptr (my computer is 64 bits).

0


source







All Articles