Sams Teach Yourself C++ in 21 Days

(singke) #1
12:
13: int main()
14: {
15: Cat Frisky;
16: Frisky.itsAge = 5; // assign to the member variable
17: std::cout << “Frisky is a cat who is “ ;
18: std::cout << Frisky.itsAge << “ years old.\n”;
19: return 0;
20: }

Frisky is a cat who is 5 years old.

Line 6 contains the keyword class. This tells the compiler that what follows is a
declaration. The name of the new class comes after the keyword class. In this
case, the name is Cat.
The body of the declaration begins with the opening brace on line 7 and ends with a
closing brace and a semicolon on line 11. Line 8 contains the keyword publicfollowed
by a colon, which indicates that everything that follows is public until the keyword
privateor the end of the class declaration.
Lines 9 and 10 contain the declarations of the class members itsAgeand itsWeight.
Line 13 begins the main()function of the program. Friskyis defined on line 15 as an
instance of a Cat—that is, as a Catobject. On line 16,Frisky’s age is set to 5. On lines
17 and 18, the itsAgemember variable is used to print out a message about Frisky.You
should notice on lines 16 and 18 how the member of the Friskyobject is accessed.
itsAgeis accessed by using the object name (Friskyin this case) followed by period
and then the member name (itsAgein this case).

OUTPUT


146 Day 6


LISTING6.1 continued

ANALYSIS

Try commenting out line 8 and try to recompile. You will receive an error on
line 16 because itsAgewill no longer have public access. Rather, itsAgeand
the other members go to the default access, which is private access.

NOTE

Making Member Data Private ........................................................................


As a general rule of design, you should keep the data members of a class private. Of
course, if you make all of the data members private, you might wonder how you access
information about the class. For example, if itsAgeis private, how would you be able to
set or get a Catobject’s age?
Free download pdf