Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 145

6


within member functions of the Catclass.” Yet, here, you’ve accessed the itsAgemem-
ber variable of the Bootsobject from outside a Catmethod. Just because Bootsis an
object of class Cat, that doesn’t mean that you can access the parts of Bootsthat are pri-
vate (even though they are visible in the declaration).
This is a source of endless confusion to new C++ programmers. I can almost hear you
yelling, “Hey! I just said Bootsis a Cat. Why can’t Bootsaccess his own age?” The
answer is that Bootscan, but you can’t. Boots, in his own methods, can access all his
parts—public and private. Even though you’ve created a Cat, that doesn’t mean that you
can see or change the parts of it that are private.
The way to use Catso that you can access the data members is to make some of the
members public:
class Cat
{
public:
unsigned int itsAge;
unsigned int itsWeight;
void Meow();
};
In this declaration,itsAge,itsWeight, and Meow()are all public. Boots.itsAge=5from
the previous example will compile without problems.

The keyword publicapplies to all members in the declaration until the key-
word privateis encountered—and vice versa. This lets you easily declare
sections of your class as public or private.

NOTE


Listing 6.1 shows the declaration of a Catclass with public member variables.

LISTING6.1 Accessing the Public Members of a Simple Class


1: // Demonstrates declaration of a class and
2: // definition of an object of the class
3:
4: #include <iostream>
5:
6: class Cat // declare the Cat class
7: {
8: public: // members that follow are public
9: int itsAge; // member variable
10: int itsWeight; // member variable
11: }; // note the semicolon
Free download pdf