In general, no you cannot assume that the size of some arbitrary class is simply the aggregation of the size of it's members. In general, nor should you care*. The compiler can and will change the size of your classes so that their size is is a multiple of some specific number of bytes. The reason it does this is to improve performance. What that number of bytes is is different for every platform.
In this specific example, it might in fact be the case that sizeof (test)
== sizeof (int)
, but I doubt this is the real code that prompted this question.
There are ways you can ensure that it does, but they rely on platform-specific functionality.
First, made sure your class is a POD* and all the members are themselves PODs.
Second, set the packing to 1 byte. Under both GCC and MSVC, the instruction to do this is similar to:
#pragma pack (1)
You should turn this packing off when it is not strictly needed, as it could have a negative impact on performance:
#pragma pack (push, 1)
class test
{
public:
void someMethod();
void someOtherMethod();
int var;
};
#pragma pack (pop)
Note that above I removed the private
section. You class is not a POD if it has nonstatic
private
or protected
data members. I also removed the default constructor and destructor for the same reason.
Under both MSVC and GCC, sizeof(test)
will equal sizeof(int)
.
POD: Plain Old Datatype. In order for a class (or struct) to be a POD, it must have no user-defined destructor or constructor, copy-assignment operator, and no non-static
members of type pointer to member. In addition, it must have no virtual
s, no private
or protected
non-static
members and no base classes. Moreover, any nonstatic
data members it does have must also be PODs themselves. In other words, just plain old (public) data.
"Nor should you care." In general, the only times you need to make sure the size of some class is exactly the size of the members is at the boundaries of the system. For example, when moving data in to or out of your program via a socket. The compiler pads your classes for a reason. You should not override the compiler in this unless you have a specific, provable cause.