Access specifiers and class member allocation order

July 28, 2009

Dan_Saks-July 28, 2009

Two months ago, I discussed Standard C's rules governing the alignment, padding and ordering of structure members.1 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. Last month, I explained how some of these elements can alter the physical layout of class objects.2 This month, I'll expand my discussion of alignment, padding and member ordering to include access control.

Access specifiers
C++ class members can have different levels of accessibility:

• A public member of a class is accessible anywhere in the program where the class itself is visible and accessible.

• A private member of a class is accessible only to members and friends of that class.

• A protected member of a class is accessible only to members and friends of that class or to members and friends of classes derived from that class.

For example, a class widget defined as:

class widget
{
public:
    widget();
protected:
    ~widget();
private:
    char m1;
    int m2;
    char m3;
    static int k;
};

has one public member function (a default constructor), one protected member function (a destructor), and four private data members (three non-static and one static).

Each access-specifier can appear more than once, and in any order. For example, you could rewrite the previous definition for widget as:


class widget
{
protected:
    ~widget();
private:
    char m1;
    int m2;
private:
    char m3;
    static int k;
public:
    widget();
};

Here the keyword private appears twice and the public member is at the end (rather than the beginning) of the class definition. These changes aren't likely to alter the size or alignment of widget objects.

< Previous
Page 1 of 4
Next >

Loading comments...

Parts Search Datasheets.com

KNOWLEDGE CENTER