Hello,
How can I make a public property in a class read-only?
It should be possible to modify it within methods of the class itself and the constructor/destructor.
Thanks in advance!
Printable View
Hello,
How can I make a public property in a class read-only?
It should be possible to modify it within methods of the class itself and the constructor/destructor.
Thanks in advance!
Make it private (within the private: section of the class), and give an accessor function. This also has the benefit that no outside code can use that variable at all.
In code:
If read_only is not a basic type but some larger struct you should return a const TYPE & instead of TYPE to avoid the copying overhead. Be aware though that badly behaving programmers could then modify the variable by const_casting the const away.Code:class A
{
private:
int read_only;
public:
int getReadonly() {
return read_only;
}
};
Ok, thanks. I was already afraid this was the only way, but I was hoping for a clever way to use const, static, or something else.