Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct constructor will take space within the struct space?

Most of the time I use struct to hold all parameters for my socket communication data structure and then I can easily copy, pass or put the entire structure on the socket by just passing the start address and its size.

If I add a constructor to the struct for a variable short array, will the constructor occupy any space within the struct? Or can I treat the struct with a constructor the same as a struct without a constructor, and copy the entire struct on to the socket with its start address and its size, and its space is still continuously allocated?

like image 294
peterboston Avatar asked Jun 01 '15 01:06

peterboston


2 Answers

No, non-virtual member functions do not contribute to the sizeof of your object. The existence of at least one virtual function contribute (however constructors cannot be virtual) since the compiler is usually implementing them via a pointer (vpointer) to an array of pointer to functions (vtable), so it must store that pointer (4 or 8 bytes usually).

like image 74
vsoftco Avatar answered Nov 14 '22 23:11

vsoftco


This question is related with C++ object model. Normal function does not increase data size. However, if we add virtual functions, the compiler will generate __vptr to point to virtual function table which will increase the data size of struct.

For example, I have a.C

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

};

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

Here, I use my IBM XL C++ Compiler in my machine to compile and run it:

xlC -+ a.C
./a.out

The output will be 8, which is the same as the struct only has 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 recompile and run it:

xlC -+ a.c
./a.out

The output will be 16. 8 for two int, 8 for __vptr (my machine is 64 bits).

like image 43
FrozenGene Avatar answered Nov 14 '22 23:11

FrozenGene