Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 171

6


Q&A ....................................................................................................................


Q How big is a class object?
A A class object’s size in memory is determined by the sum of the sizes of its mem-
ber variables. Class methods take up just a small amount of memory, which is used
to store information on the location of the method (a pointer).
Some compilers align variables in memory in such a way that two-byte variables
actually consume somewhat more than two bytes. Check your compiler manual to
be certain, but at this point you do not need to be concerned with these details.
Q If I declare a class Catwith a private member itsAgeand then define two Cat
objects,Friskyand Boots, can Bootsaccess Frisky’s itsAgemember variable?
A No. Different instances of a class can access each other’s nonpublic data. In other
words, if Friskyand Bootsare both instances of Cat,Frisky’s member functions
can access Frisky’s data and but not Boots’s data.
Q Why shouldn’t I make all the member data public?
A Making member data private enables the client of the class to use the data without
being dependent on how it is stored or computed. For example, if the Catclass has
a method GetAge(), clients of the Catclass can ask for the Cat’s age without
knowing or caring if the Catstores its age in a member variable or computes its
age on-the-fly. This means the programmer of the Catclass can change the design
of the Catclass in the future without requiring all of the users of Catto change
their programs as well.
Q If using a constfunction to change the class causes a compiler error, why
shouldn’t I just leave out the word constand be certain to avoid errors?
A If your member function logically shouldn’t change the class, using the keyword
constis a good way to enlist the compiler in helping you find mistakes. For exam-
ple,GetAge()might have no reason to change the Catclass, but your implementa-
tion has this line:
if (itsAge = 100) cout << “Hey! You’re 100 years old\n”;
Declaring GetAge()to be constcauses this code to be flagged as an error. You
meant to check whether itsAgeis equal to 100, but instead you inadvertently
assigned 100 to itsAge. Because this assignment changes the class—and you said
this method would not change the class—the compiler is able to find the error.
This kind of mistake can be hard to find just by scanning the code. The eye often
sees only what it expects to see. More importantly, the program might appear to
run correctly, but itsAgehas now been set to a bogus number. This causes prob-
lems sooner or later.
Free download pdf