<< PreviousNext >>

Public read-only data

When you want to have a read-only data member in a C++ class, you can declare it as const to make the compiler help you enforce the read-only property. Sometimes, however, you want your data member to be read-only to everyone outside the class, but you need to modify it yourself.

This is commonly solved by implementing something like this:

class C {
public:
    C() : myData(0) {}

    void update() { myData++; }

    inline int data() const { return myData; }

private:
    int myData;
};

In this case, we want to allow certain controlled updates to the myData field through the update member. Therefore we can not declare myData as const. However, everyone using the class need to call the function to access the data:

int f() {
    C c;
    c.update();
    std::cout << c.data() << std::endl;
}

But, can we re-design our class so that the following code works?

int f() {
    C c;
    c.update();
    std::cout << c.data << std::endl;
}

Note that the only difference is that c.data() is replaced with c.data. Of course, assignments to c.data should still not be allowed.

Answer and comments