2.3.  Member Access Specifiers

[ fromfile: classes.xml id: memberaccess ]

Example 2.5. src/classes/fraction/fraction.h

#ifndef _FRACTION_H_ 
#define _FRACTION_H_  

#include <QString>


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

#endif


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

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

int main() {
    const int DASHES = 30;
    QTextStream cout(stdout);
    
    {                                   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.




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

[14] Chapter 6 discuss derived classes.

[15] Private members are also accessible by friends of the class, which we discuss in Section 2.6.