piątek, 15 sierpnia 2008

More constraints, please

In C++ classes have public, protected and private members. Variable member can be also declared as const or static const and it make such member read-only.

But it would be really great if we can select level of protection, and declare that some variable is const only when accessed at public or protected level. Here is a sample:

class C1 { // C++ - present
void foo_x() { /* do some magic with x */ x = 5; }
int get_x() const { return x;}

int x;

class C2 { // C++ - future?
void foo_x() { /* do some magic with x */ x = 5; }

public const:
int x;

Member x can be freely read/write within C2 member functions, but when accessed from outside, x is read only.

This is not as powerful as Borland's extension __property, which allow to declare property as alias for member variable, or setup getter/setter for a property. However I think proposed extension wouldn't bring much work for compilers authors.

Brak komentarzy: