Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ object sizes

Tags:

c++

Suppose I have:

struct Foo: public Bar {
 ....
}

Foo introduces no new member varaibles. Foo only introduces a bunch of member functions & static functions. Does any part of the C++ standard now guarantee me that:

sizeof(Foo) == sizeof(Bar)

?

Thanks!

like image 951
anon Avatar asked May 07 '10 00:05

anon


3 Answers

I could think of at least one scenario where sizeof(Foo) != sizeof(Bar):

class Bar {
public:
 int m_member;
};

class Foo : Bar {
    virtual ~Foo();
};

Foo will have a vtable pointer whilst Bar wouldn't and the former's size will be one word bigger that Bar. On 32bit DEBUG MSVC2010:

sizeof(Foo) - 8
sizeof(Bar) - 4

EDIT This holds true for structs as well as classes, I reran the test to confirm that.

like image 118
Igor Zevaka Avatar answered Nov 06 '22 02:11

Igor Zevaka


Yes - if they are POD types. POD types are guarenteed to be layout compatable (that is you can memcpy from one to the other) if they have layout-compatable members in the same order. Since a subclass automatically has all of its base class's members in the same order and, in this case, no others, they will be layout compatible and thus the same size. See section 9.3 of the spec.

Note that in order to be POD types they must have no virtual functions (among other requirements)

EDIT

The latest draft standard has split the requirements for POD types into two sets: trivial classes and standard layout classes. POD classes are those that are both trivial and standard layout, and I believe for the sizeof guarentee you want, just being standard layout suffices -- they need not also be trivial (and thus POD) classes. The requirements for standard layout from the spec are:

A standard-layout class is a class that:

— has no non-static data members of type non-standard-layout class (or array of such types) or reference,

— has no virtual functions (10.3) and no virtual base classes (10.1),

— has the same access control (Clause 11) for all non-static data members,

— has no non-standard-layout base classes,

— either has no non-static data members in the most-derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

— has no base classes of the same type as the first non-static data member.108

like image 21
Chris Dodd Avatar answered Nov 06 '22 02:11

Chris Dodd


Certainly not, especially if any of the functions in either of your classes are virtual. While the C++ standard doesn't guarantee this, having virtual functions would almost certainly change the size of your objects (because of v-tables.)

like image 32
Adam Maras Avatar answered Nov 06 '22 02:11

Adam Maras