[LC++]Is there a place for public data members?
Mark Phillips
mark at austrics.com.au
Tue Nov 6 11:41:04 UTC 2001
Thanks for the feedback!
Carlo Wood wrote:
>
> 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.
I have been thinking of the public interface as comprising "modifiers",
on the one hand, and "attributes" on the other. In my understanding
a modifier method would actually modify the object; change something
internally. An attribute method on the other hand, gleans some piece
of information from the object. Using this classification, your
"get_myInt" is an attribute interface whereas your "set_myInt"
is a modifier interface. Do you see problems with my way of thinking
about the public interface?
I don't see the advantage of having "get_myInt()" instead of just "myInt()"
but I do see and advantage of "set_myInt()" over just returning an
address for the myInt private member. Suppose instead of just returning
private int member, we wanted to "calculate" the integer, for example, using
an offset:
class myClassTy {
private:
int const offsetVt=23;
int dataVt;
public:
int myInt() const {return offsetVt+dataVt;}
...
Changing myClassTy in this way would break my interface, because my
approach to setting the attribute was just to return an "int&". Using
your approach to setting would give:
class myClassTy {
private:
int const offsetVt=23;
int dataVt;
public:
int myInt() const {return offsetVt+dataVt;}
void setMyInt(int const& myIntAg) {dataVt=myIntAg-offsetVt;}
};
So your means of setting is better, but I still like the idea of
using "myInt()" rather than "getMyInt()" as I don't see what's
wrong with saying "this is the attribute" rather than just "I am
going to get the attribute for you". Is this issue just a matter
of taste, or am I missing something more significant?
Cheers,
Mark.
More information about the tuxCPProgramming
mailing list