Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

4 bytes in the a non-virtual class get reserved,can't figure out what?

Status
Not open for further replies.

michelle1278

Programmer
May 20, 2004
1
US
I have the following class hierarchy:

Class Base
{
void baseFoo();
//some more functions
private:
int baseIdx;
};

class Derived : public Base
{
void derFoo();
//some more functions
private:
int spvar;
};

then object of type Derived:
Derived derObj;

When I checked the memory layout of "derObj", the first 4 bytes of the object are reserved. The value of the int baseIdx starts at the 5th byte.

I cannot understand why those first 4 bytes are reserved, there's no virtual functions/ vtable involved in this class hierarchy.
 
What do the first 4 bytes look like? Do they point to a vtable or is it something else? Did you turn on RTTI, maybe?
 
In regular compilation mode (no RTTI and other exotics) all member addresses are OK: &object == &base member var (VC++ SP5)...
 
I believe it is because they are declared as a class. I would assume that this is related to why a sizeof(class) will not always be the size of the member data but a sizeof(struct) will be. You could change them to a struct instead of a class and retain the inheritance if you want to ensure the memory is as expected.

Matt
 
No any 'sizeof differences' between classes and structures in C++.
sizeof(class|struct) != sum(sizeof(members)) when memory align needed (or a class/structure has virtual functions - vtbl ptr added). RTTI support (as usually) implemented via vtbl (see teriviret's post)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top