[LC++]Is there a place for public data members?
Carlo Wood
carlo at alinoe.com
Tue Nov 6 01:45:03 UTC 2001
On Mon, Nov 05, 2001 at 06:48:54PM +1030, Mark Phillips wrote:
> Hi,
>
> Instead of doing
>
> class myClassTy {
> public:
> int myInt;
> };
>
> another approach is to do:
>
> class myClassTy {
> private:
> int myIntVt;
> public:
> int myInt() const {return myIntVt;}
> int& myInt() {return myIntVt;}
> };
The fact that myInt is public makes it that you can't
change myClassTy in a way that this integer changes
it's meaning. The second approach has the same effect.
Both are "bad", and therefore I'd prefer the first
one for simplicity.
The following is a better approach,
class myClassTy {
private:
int M_myInt;
public:
int get_myInt(void) const { return M_myInt; }
void set_myInt(int myInt) { M_myInt = myInt; }
};
You should think of class methods as "operators" that operate
on the object. You should give them a name that reflects the
true meaning of the operator/method.
For example, if the `M_myInt' in the above reflects
the text color, then instead of giving direct access
to a variable `M_color' you'd rather define:
Color get_text_color(void) const;
void set_text_color(Color const&);
Assuming that the nature of the class defines `text'
clearly - then the meaning of this interface is safe
(even though you can later change what a 'Color' is).
--
Carlo Wood <carlo at alinoe.com>
More information about the tuxCPProgramming
mailing list