Partilhar via


Access Specifiers

In class declarations, members can have access specifiers.

Grammar

access-specifier : member-listopt

  • access-specifier: one of
    private

    public

    protected

The access-specifier determines the access to the names that follow it, up to the next access-specifier or the end of the class declaration. The following figure illustrates this concept.

Access Control in Classes

Access Control Classes

Although only two access specifiers are shown in the figure, there is no limit to the number of access specifiers in a given class declaration. For example, the Point class in the figure could just as easily be declared using multiple access specifiers as follows:

// access_specifiers1.cpp
class Point
{
public:                  // Declare public constructor.
    Point( int, int );
private:                 // Declare private state variable.
    int _x;
public:                  // Declare public constructor.
    Point();
public:                  // Declare public accessor.
    int &x( int );
private:                 // Declare private state variable.
    int _y;
public:                  // Declare public accessor.
    int &y( int );
};

int main()
{
}

Note that there is no specific order required for member access, as shown in the preceding example. The allocation of storage for objects of class types is implementation dependent, but members are guaranteed to be assigned successively higher memory addresses between access specifiers.

See Also

Reference

Member-Access Control