2

Suppose:

Class A{
  float one;
  float two;
  float three;
 //... many, many member functions, and maybe static functions too ..
  }

Can I assume that, no matter how many functions are in this class, the following should generally be true:

sizeof(A)==sizeof(float)*3

Such that I could even assert this:

static_assert(sizeof(A) == sizeof(float) * 3, "Your class is padding memory.");

Is this accurate?

Now, suppose class A inherits from another class. I assume the above would not be true, and rather you'd have to include in the sizeof assertion the addition of the size of ivars from the base class?

johnbakers
  • 23,563
  • 21
  • 114
  • 241

2 Answers2

1

if "Class A" has virtual functions or derives from class(es) having virtual methods then the sizeof(A) cannot be accurately determined by manually summing up the data members.

This is because compiler inserts a hidden pointer called as v-pointer which points to v-table.

Things get more complicated if you have virtual base class, since a hidden v-base-pointer might get inserted by the compiler.

Also, the position where these hidden pointers get inserted within the memory model of a polymorphic C++ object changes across compiler implementation (since these specifics are not part of the C++ standard). This is one such reason why we can't achieve binary interface compatibility (Compile once and reuse across all platforms) of applications developed using C++. (Again, this is another reason why .Net and Java was invented!).

In short, the memory model of a polymorphic class in "C++" doesn't match with that of "C" (that's one reason why we have extern "C" in C++).

Arun
  • 2,055
  • 2
  • 19
  • 33
0
many, many member functions, and maybe static functions too

If you class A contains virtual functions, then

sizeof(A)==sizeof(float)*3

will not be true since there is extra memory for vtable/vptr.

taocp
  • 22,732
  • 9
  • 48
  • 60