Is there a generic way (not platform dependent) to get at compile time the size of a class object in the memory, without counting the vtable pointers?
Asked
Active
Viewed 1,224 times
2
-
3What's wrong with `sizeof`? It does not include the size of vtable, only the size of a pointer to vtable, if any. – Sergey Kalinichenko Feb 10 '15 at 14:23
-
Subtraction? What if there is more than one? – Reflection Feb 10 '15 at 14:29
-
1Out of curiosity: what for? – Angew is no longer proud of SO Feb 10 '15 at 14:43
-
4A vtable is already something platform-dependent. The C++ standard does not mandate the use of vtables to implement virtual functions. – Christian Hackl Feb 10 '15 at 15:59
-
You need to consult the description of the memory layout of object on your platform, if there is one, to know the location of the vptrs. You will learn of the layout of virtual base, what a primary base is, etc. – curiousguy Aug 01 '15 at 00:54
2 Answers
1
As you are asking for a portable way:
class MyClass
{
private:
struct S
{
DataMemberType1 dataMember1;
...
DataMemberTypeN dataMemberN;
} m;
public:
static const size_t MemberSize = sizeof(S);
};

ur.
- 2,890
- 1
- 18
- 21
-
Are you sure this is 100% portable and `sizeof(MyClass) - sizeof(S)` will always be exactly equal to the size of the vpointer? – Neil Kirk Feb 10 '15 at 14:45
-
@Neil: My solution avoids the implementation specific details. Have a short look at "How are C++ objects laid out in memory?" [link](http://www.stroustrup.com/bs_faq2.html#layout-obj). – ur. Feb 10 '15 at 15:02
-
-
@Neil: Yes, you can expect padding, but it should make no difference as you have the same padding in 'class' as in 'struct' – ur. Feb 10 '15 at 15:35
-
0
Use sizeof
on this class
, it doesn't include size of the vtable
just the pointer.

Paul Evans
- 27,315
- 3
- 37
- 54
-
@PaulEvans Your answer is false for any object that has virtual functions (any object actually containing a vtable.) http://ideone.com/7y48aO – Jonathan Mee Jul 14 '15 at 12:24
-
@JonathanMee The answer is correct; class instances contains a vptr (short for vtable pointer) **not** a vtable (table of function pointers for virtual functions of the class + RTTI info + virtual bases offset) – curiousguy Aug 01 '15 at 00:52