Sams Teach Yourself C++ in 21 Days

(singke) #1
compiler knows that Friskycan’t bark because the Catclass doesn’t have a Bark()
method. The compiler wouldn’t even let Friskymeow if you didn’t define a Meow()
function.

144 Day 6


DOuse the keyword classto declare a
class.
DOuse the dot operator (.) to access
class members and functions.

DON’Tconfuse a declaration with a defi-
nition. A declaration says what a class is.
A definition sets aside memory for an
object.
DON’Tconfuse a class with an object.
DON’Tassign values to a class. Assign val-
ues to the data members of an object.

DO DON’T


Private Versus Public Access ..............................................................................


Additional keywords are often used in the declaration of a class. Two of the most impor-
tant are publicand private.
The privateand publickeywords are used with members of a class—both data mem-
bers and member methods. Private members can be accessed only within methods of the
class itself. Public members can be accessed through any object of the class. This distinc-
tion is both important and confusing. All members of a class are private, by default.
To make this a bit clearer, consider an example from earlier:
class Cat
{
unsigned int itsAge;
unsigned int itsWeight;
void Meow();
};
In this declaration,itsAge,itsWeight, and Meow()are all private because all members
of a class are private by default. Unless you specify otherwise, they are private. If you
create a program and try to write the following within main(for example):
int main()
{
Cat Boots;
Boots.itsAge=5; // error! can’t access private data!
...
the compiler flags this as an error. In effect, by leaving these members as private,
you’ve said to the compiler, “I’ll access itsAge,itsWeight, and Meow()only from
Free download pdf