@ helios:
It depends on what the class does, really. If 'number' could have an impact on other variables or another state of the class, then it's best to have it in a set/get system rather than having direct access so the state changes can be made.
Say for example you have a class which represents a Line. It has two points, A and B. It might make sense to have A and B be public members. But what if you want it to do something else, like keep track of the length of the line?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Line
{
public:
void SetA(const Point& a){ A = a; MakeDirty(); }
void SetB(const Point& b){ B = b; MakeDirty(); }
Point GetA() const { return A; }
Point GetB() const { return B; }
double GetLength()
{
if( IsDirty() )
{
Point c(A - B);
length = sqrt( (c.x * c.x) + (c.y * c.y) );
MakeClean();
}
return length;
}
private:
Point A, B;
double length;
// dirty stuff here
};
|
This approach means the length is only recalculated when needed. Of course this isn't necessary (and there's an argument for why it's not a good idea -- const correctness comes to mind immediately), but this is just an example of why you'd want something like this.
Also, if the functions are inlined they're not slower.
Even if you don't have need for a get/set interface right away... you may change the class to require one in the future. And if you have the members public, this means you have to change the entire interface for the class and rewrite all of your code that uses the class (could be a big job), so there's a argument for putting in Get/Set functions in from the get-go.
ALL OF THAT SAID:
I agree with you that it probably isn't necessary in this case. And while I list the rationale for the get/set approach above, I don't believe that you should always put get/set functions everywhere. A lot of the time, you're really better off with public members. I don't agree with gcampton that having public members is "bad concept". I think needlessly making a million get/set functions for every property is a bad concept.
But it really does depend on the situation. This is one of those things where there is no "one size fits all" solution. Use what's best for the task at hand.