Wednesday, June 13, 2007

3.0 The Semantics of Data

class X{}; // size: 1
class Y : public virtual X {}; // size: 8
class Z : public virtual X {}; // size: 8
class A : public Y, public Z {}; // size: 12

class X {} in pratice is never empty. Rather it has an associated size of 1 byte - a char member inserted by the compiler. This allows two objects of the class to be allocated unique addresses in memory.

The class Y and Z size on any machine is the interplay of three factors:
1. Language support overhead. There is an associated overhead incurred in the language support of virtual base classes.
2. Compiler optimization or recognized special cases. There is the 1 byte size of the virtual base class X subobject also present within Y and Z (Potential optimiazation is desired).
3. Alignment constraits. On most machines, aggregate structures have an alignment constraint so that they can be efficiently loaded from and stored to memory.

The empty virtual base class has become a common idiom of OO design under C++. It provides a virtual interface without defining any data. Some recent compilers provide special handling and an empty virtual base class is treated as being coincident with the beginning of the derived class object.

A virtual base class subobject occurs only once in the derived class regardless of the number of times it occurs within the class inheritance hierarchy.

The C++ standard does not mandate details such as the ordering of either base class subobjects or of data members across access levels. Stanley distinguish between what the Standard mandates and what the current standard practice is.

Nonstatic data members hold the values of individual class objects; static data members hold values of interest to the class as a whole. Static data members are maintained within the global data segment of the program and do not affect the size of individual class objects.

The object size may at times surprise you as being larger than necessary in two ways:
1. Additional data members added by the compilation system to support some language functionality
2. Alignment requirements on the data members and data structures as a whole

No comments: