Does the C++ spec allow an instance of a non-virtual class to include memory for a vtable pointer? I am asking this, because a colleague said he once used a C++ compiler where the following happened:
class MyClass
{
public:
HeaderStruct header; //This had extra words
BodyStruct message_body;
};
He then changed the code to this, which got rid of the extra words:
struct MyClass
{
HeaderStruct header; //This did not have extra words
BodyStruct message_body;
};
None of these types was virtual or derived from anything virtual. So the theory was that perhaps this particular compiler allocated memory for a vptr for the class instances but not for the struct instances. So I'm just trying to determine if such compiler behavior is precluded by the spec.
Thanks!
Ken
I'm unable to find an online reference for it with a quick search, but I'm pretty sure a compiler is permitted to do ANYTHING with the layout of any class; in particular, in classes without any virtual methods, it's allowed to put a vftp or not, depending on how it's feeling that day, whether it's declared as class
or struct
(which are equivalent in C++ except for the default access specifier), the phase of the moon, or anything else. The only restriction that I'm aware of is that the top part of a derived object shall match the layout of its first (non-virtual) base class. And I'm not even sure it has to be the first one.
You should not at any time depend on a particular compiler's decision on the layout of an object. Many compilers put a vftp in all objects without exception, in order to provide run-time type information to debuggers, or just to make their own lives easier. Some don't. You have no reasonable way of knowing, except through the sizeof
operator.