Advertisement

Classes are structures, and then some

July 01, 2009

Dan_Saks-July 01, 2009

Last month I discussed Standard C's rules governing the alignment, padding and ordering of structure members.i For the most part, C code that defines and uses structures behaves the same when compiled and executed as C++. However, C++ generalizes structures into classes. A C++ class can have elements that a C structure cannot, such as access specifiers, member functions, static data members, and base classes. This month, I'll explain how some of these elements alter the physical layout of class objects.

The C++ Standard says a lot about classes, but hardly anything about structures. C++ treats structures as just classes declared in a slightly different way. According to the C++ Standard, "A structure is a class defined with the [keyword] struct; its members and base classes ... are public by default."ii In a class defined with the keyword class, the members and bases are private by default.

For example, in C++, the structure definition:


struct widget
{
    char m1;
    int m2;
    char m3;
};

is actually equivalent to the class definition:


class widget
{
public: 
    char m1;
    int m2;
    char m3;}
;

As a class, widget has the same size and alignment as it does as a structure. Each class member has the same size, allocation order, alignment and padding as it does in the structure. When compiled for a target machine in which each int occupies four bytes aligned to an address that's a multiple of four, the compiler will insert three bytes of padding after each of the char members, as if the class had been defined as:



class widget
{
public:
    char m1;
    char padding_after_m1[3];     
    int m2;
    char m3;
    char padding_after_m3[3];     
};

The keyword public is one of three possible access-specifiers, the others being private and protected. The access-specifiers themselves don't occupy any data storage.

< Previous
Page 1 of 2
Next >

Loading comments...