Re: Public attributes: R/W within class, R/O outside class
On 10/01/2010 2:12 AM, , wrote:
Is there a way to make a class attribute public in a way that it can be read
or written from within its class, but only read from outside the class?
I'm looking for a way other than making it private and accessing via
accessor methods.
If it is the appearance of the accessor methods in client code that is
bothering you (versus the need to write the accessor methods
themselves), then perhaps something like the following?
template<
class T, // Type being wrapped.
class P > // Parent class to be allowed access.
class ReadOnly
{
public:
ReadOnly(const T& param) : value_(param) { }
operator T () const { return value_; }
private:
ReadOnly& operator = (const T& param)
{
value_ = param;
return *this;
}
T value_;
friend typename P;
};
class ParentType
{
public:
ParentType(int param) : my_value(param) { }
/// Object that can be read, but not written outside Parent.
ReadOnly<int, ParentType> my_value;
void OtherFn() { my_value = 2; }
};
#include <iostream>
int main()
{
ParentType a(1);
std::cout << a.my_value << std::endl;
a.OtherFn();
std::cout << a.my_value << std::endl;
//a.my_value = 3; /// Error.
return 0;
}