Jan M.
Jan M.

Reputation: 501

Public const variable or private with a get function, which is preferable?

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
}

Upvotes: 0

Views: 90

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258638

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.

Upvotes: 5

Related Questions