Ask your own question, for FREE!
Computer Science 11 Online
OpenStudy (anonymous):

In introductory CS classes that teach C++, why do they make us go through the trouble of declaring variables private and implementing getters and setters for all our classes if we do nothing special with them apart from bookkeeping data; why not use structs instead?

OpenStudy (rsmith6559):

structs have no access controls, classes do. AFAIK, that's the main difference between them.

OpenStudy (anonymous):

right; all stuff in structs are 'public' by default, whereas all stuff in classes are 'private' by default.

OpenStudy (anonymous):

This makes me remember that someone (important) said that C++ is a horrible language to be taught in Intro to CS classes, haha. :-)

OpenStudy (anonymous):

idk what's the difference in c++ but in java instance variables always should be private unless you have a good reason for it not to be, so other classes wouldn't change those variables by accident (or maybe not >:) ) and yeah in simple programs where you have 1 or few classes it doesn't really mater but it's good practise to do that way, so you won't mix it in real programs

OpenStudy (s3a):

One good reason is: A setter may update more than the one variable in a non-obvious way. And the getter is needed just because it's declared private to enforce the use of the setter. Maybe a class about sports could have something like setGoals(int goals) which would update the amount of goals but also how many wins/losses/ties that implies. If you did this without the setter, you'd be updating a goals field while neglecting wins/losses/ties.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!