|
-
Dec 14th, 2002, 05:49 PM
#1
Thread Starter
Fanatic Member
readonly class property
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!
-
Dec 14th, 2002, 06:40 PM
#2
Monday Morning Lunatic
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.
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Dec 14th, 2002, 08:39 PM
#3
In code:
Code:
class A
{
private:
int read_only;
public:
int getReadonly() {
return read_only;
}
};
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.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Dec 15th, 2002, 03:04 AM
#4
Thread Starter
Fanatic Member
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|