See what's going on with flipcode!




This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  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.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.