2.3.  Member Access Specifiers

[ fromfile: classes.xml id: memberaccess ]

Thus far we have worked with class definition code (header files, containing class definitions and other declarations), and class implementation code (the header's corresponding .cpp file containing definitions missing from the header file). There is a third category of code as it relates to a given class. Client code is code that is outside the scope of the class, but which uses objects or members of that class. Generally, client code #includes the header file that contains the class definition.

Example 2.5. src/classes/fraction.h

#ifndef _FRACTION_H_ 
#define _FRACTION_H_  

#include <string>
using namespace std;

class Fraction {
public:
    void set(int numerator, int denominator);
    double toDouble() const;
    string toString() const;
private:
    int m_Numerator;
    int m_Denominator;
};

#endif


The access specifiers, public, protected, and private, are used in a class definition to specify where in a program the affected members can be accessed. The following list provides an informal first approximation of the definitions of these three terms. Refinements are contained in footnotes.

Example 2.6 shows some client code to demonstrate visibility errors in a variety of ways. This example also focuses on block scope which extends from an opening brace to a closing brace. A variable declared inside a block is visible and accessible only between its declaration and the closing brace. In the case of a function, the block that contains the function definition also includes the function's parameter list.

Example 2.6. src/classes/fraction-client.cpp

#include "fraction.h"
#include <iostream>

int main() {
    const int DASHES = 30;
    using namespace std;
    
    {   1
        int i;
        for (i = 0; i < DASHES; ++i)
            cout << "=";
        cout << endl;
    }   

    // cout << "i = " << i << endl;  2
    Fraction f1, f2;
    f1.set(3, 4);
    f2.set(11,12);  3
    // f2.m_Numerator = 12; 4
    cout << "The first fraction is: " << f1.toString() << endl;
    cout << "\nThe second fraction, expressed as a double is: "
         << f2.toDouble() << endl;
    return 0;
}

1

nested scope, inner block

2

error, i no longer exists, so it is not visible in this scope.

3

set through a member function

4

error, m_Numerator is visible but not accessible.

Now we can describe the difference between struct and class in C++. Stroustrup defines a struct to be a class in which members are by default public, so that

 struct T { ... 

means precisely:

 class T {public: ...  



[12] public static members can be accessed without an object. We discuss this in Section 2.10

[13] We discuss derived classes in Chapter 6

[14] Private members are also accessible by friends of the class, which we discus in Section 2.7