Tuesday, November 28, 2006

C++: Read-only member function

class MyClass
{
private:
int _AsInteger;
public:
const int &AsInteger;

MyClass() : _AsInteger(0), AsInteger(_AsInteger)
{
}

void SetDefault()
{
_AsInteger= 17;
}
};


MyClass obj1;
int a = obj1.AsInteger; //success
obj1.AsInteger= 1337; //compiler error
This way, you have a member that appears public but really isn't.

No comments: