0

So I have a variable I often have to call outside the class, I was told that I should do this:

class Foo{
    public:
        //stuff
    Type getVariable();
    private:
        Type Variable;
        //stuff
}

But why can't I just use:

class Foo{
    public:
        //stuff
    const Type variable
    private:
        //stuff
}
Jan M.
  • 489
  • 2
  • 5
  • 21

1 Answers1

5

You can, but don't expect the same results.

In the second case, you can't modify variable anymore, not even inside the functions.

They're different things.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • But in terms of "security", it comes down to the same thing? Would this be the only aspect that distinguishes these two? – Jan M. Mar 26 '13 at 16:47
  • @PatronBernard no, **all** aspects distinguish the two. They're completely unrelated. – Luchian Grigore Mar 26 '13 at 16:48
  • @PatronBernard, public vs. private is merely a compile time check. It's not really "security". I could still access the variable and modify it, given sufficient motivation. `const` possibly allows the compiler to move the storage into a read-only memory area, and attempts to modify it would cause an access violation, but this varies wildly by compiler and architecture. – Nathan Ernst Mar 26 '13 at 21:31