Class Members

Classes can have these kinds of members:

Remarks

The member list of a class may be divided into private, protected and public sections using keywords known as access specifiers. A colon : must follow the access specifier. These sections need not be contiguous, that is, any of these keywords may appear several times in the member list. The keyword designates the access of all members up until the next access specifier or the closing brace.

Member declarations in the member list are separated by semicolons ;. See Class-Member Declaration Syntax.

The purpose of the member list is to:

  • Declare the complete set of members for a given class.

  • Specify the access (public, private, or protected) associated with various class members.

In the declaration of a member list, you can declare members only once; redeclaration of members produces an error message. Because a member list is a complete set of the members, you cannot add members to a given class with subsequent class declarations.

Member declarators cannot contain initializers. Supplying an initializer produces an error message as illustrated in the following code:

// class_members1.cpp
// C2864 expected
class CantInit
{
public:
    long l = 7;       // Error: attempt to initialize
                      //  class member.
    static int i = 9; // Error: must be defined and initialized
                      // outside of class declaration.
};
int main()
{
}

Because a separate instance of nonstatic member data is created for each object of a given class type, the correct way to initialize member data is to use the class's constructor. (Constructors are covered in Constructors,.)

There is only one shared copy of static data members for all objects of a given class type. Static data members must be defined and can be initialized at file scope. (For more information about static data members, see Static Data Members.) The following example shows how to perform these initializations:

// class_members2.cpp
class CanInit
{
public:
    CanInit() { l = 7; } // Initializes l when new objects of type 
                         //  CanInit are created.
    long       l;
    static int i;
    static int j;
};

// i is defined at file scope and initialized to 15.
// The initializer is evaluated in the scope of CanInit.
int CanInit::i = 15;                                                       

// The right side of the initializer is in the scope 
// of the object being initialized
int CanInit::j = i;  

int main()
{
}

Hinweis

The class name, CanInit, must precede i to specify that the i being defined is a member of class CanInit.

Microsoft Specific

Microsoft C++ allows static, const integral, and const enum data members to be initialized in the class definition. See Microsoft Extensions to C and C++.

See Also

Concepts

Classes, Structures, and Unions