3

Let's say I have a struct like this:

struct 64BitStruct
{
    uint64_t value;
    void SomeFunction(bool enable);
    bool SomeOtherFunction();
};

sizeof(64BitStruct) returns 8 bytes, which is 64 bits. I assume those 64bits are the value variable in the struct, but then where are the functions stored?

Kyota.exe
  • 115
  • 1
  • 10
  • All actual code from all functions in the program (global, namespace or member functions) are collected into a single section of the executable file, and loaded into memory by the operating system somewhere. – Some programmer dude Dec 15 '21 at 19:07
  • `void SomeFunction(bool enable);` `bool SomeOtherFunction();` are declarations of member functions, so they don't contribute to the size of the struct. So they don't represent an "instance-specific" concept, but a class wide concept. So the code for these functions is stored in the `.text` section - like any other code, such as the one inside `main`. You might be confusing function declarations with pointer to functions, which would contribute to the size of the class, and would allow for different instances of that struct to point to different functions. – Julien BERNARD Dec 15 '21 at 19:10
  • Functions do not occupy space in the object for the same reason `static` member variables do not occupy object space. There only needs to exist one instance of the function, used by all object instances. – Drew Dormann Dec 15 '21 at 19:14

1 Answers1

3

Member functions are common functions of all objects of the structure type. So they are stored separately from objects. The size of the structure in your example is in fact the size of its data member. If a structure has virtual functions then it implicitly includes a pointer to the table of virtual function pointers as a data member for each object of the structure type.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335