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
  • 24,158
  • 24
  • 130
  • 258
  • 2
    Why not just try and see what happens? – Bala R Apr 12 '13 at 01:57
  • possible dupe of http://stackoverflow.com/questions/6552319/c-sizeof-of-a-class-with-functions and http://stackoverflow.com/questions/4338966/c-how-can-i-know-the-size-of-base-class-subobject/ – Rapptz Apr 12 '13 at 01:58
  • 1
    This answer sums up the issues pretty well: http://stackoverflow.com/a/937800 – Shafik Yaghmour Apr 12 '13 at 02:05
  • @BalaR Because it would be implementation-dependant results. We ask these sort of questions to know _what the standard say about this_, as that’s the only thing we should care about. – Константин Ван Jan 18 '21 at 22:06

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,087
  • 2
  • 20
  • 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
  • 23,276
  • 10
  • 49
  • 62