Results 1 to 4 of 4

Thread: readonly class property

  1. #1

    Thread Starter
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551

    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!

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    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

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    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.

  4. #4

    Thread Starter
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551
    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
  •  



Click Here to Expand Forum to Full Width