| 
 
| 
|  | Read-Only Data Member Submitted by
 |  
  
 Here is a modest but handy tip. Sometimes it would
be useful to have read-only public data member.
 
 Let's take a very basic example:
 
 
 | class counter {
public:
    int n;
 counter() : n(0) {}
 
 void increment() {
        n++;
    }
};
 | 
 
 The problem with this code is that n can be freely
modified by anybody. We could prevent that by making
n private, but then we would have to write a method to
read its value.
 
 The solution is to make n private and to add a public
constant reference to it:
 
 
 
 
 | class counter {
    int n;
public:
    const int &value;
 counter() : n(0), value(n) {}
 
 void increment() {
        n++;
    }
};
 | 
 
 
 
 Thus, n can't be modified outside the counter class,
while it can be read through the value data member:
 
 
 | void f() {
    counter c;
 cout << c.value << endl; // allowed, will output 0
    c.increment();
 
 cout << c.value << endl; // allowed, will output 1
    c.value++;   // forbidden, will produce a compile error
}
 | 
 
 Cheers,
 Francois.
 
 
 |  The zip file viewer built into the Developer Toolbox made use
of the zlib library, as well as the zlibdll source additions.
 
 |