TITLE: simulating read-only data member AUTHOR: p j l @kronos.arc.nasa.gov (Paul J. Lucas), 4 Dec 95 Given: class C { public: int const &x, &y; C() : x( x_ ), y( y_ ) { } private: int x_, y_; }; The idea is to allow non-member functions have read-only access having the syntax of: cout << instance.x << endl; instead of the usual: cout << instance.x() << endl; [ The "usual" approach is to add an access method for a given data member. So the issue is public references versus public access methods. -adc ] But the question is: Will a good compiler optimize the indirection through the reference out of existence? (Yes, I would really like not to force the user to use ()s since the C++ code for the class declarations is machine-generated. I'd like the user's declaration of x not to mutate into x().) (Also, I don't expect the compiler to be able to optimize the storage for the reference in the class out of existence; but, I may be willing to live with that.) It occurred to me while typing this that I could do: template< class T, class Friend > class read_only { public: read_only() { } read_only( T data ) : data_( data ) { } operator T() const { return data_; } private: T data_; read_only< T, Friend >& operator=( T data ) { data_ = data; return *this; } friend class Friend; }; class C { public: read_only< int, C > x; void f() { x = 42; // class C can change x } }; main() { C c; int i = c.x; // ok: read-only access c.x = 12; // error: operator=() not accessible } [...]