Login    New User    Forgot Password    Help      

All Members of a Class


All members of a class--data and methods--are private by default. Private members can be accessed only within methods of the class itself. Public members can be accessed through any object of the class. This distinction is both important and confusing. To make it a bit clearer, consider an example:

class Cat  
{  unsigned int  itsAge;  
unsigned int  itsWeight; 
 Meow();  };  

In this declaration, itsAge, itsWeight, and Meow() are all private, because all members of a class are private by default. This means that unless you specify otherwise, they are private.

However, if you write

Cat  Boots; 
Boots.itsAge=5;        // error! can't access private data!  

the compiler flags this as an error. In effect, you've said to the compiler, "I'll access itsAge,itsWeight, and Meow() only from within member functions of the Cat class." Yet here you've accessed the itsAge member variable of the Boots object from outside a Cat method. Just becauseBoots is an object of class Cat, that doesn't mean that you can access the parts of Boots that are private.

This is a source of endless confusion to new C++ programmers. I can almost hear you yelling, "Hey! I just said Boots is a cat. Why can't Boots access his own age?" The answer is that Boots can, 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 Cat so that you can access the data members is

class Cat  
{  public:  unsigned 
int  itsAge;  unsigned int  itsWeight;  
Meow();  };  

Now itsAge, itsWeight, and Meow() are all public. Boots.itsAge=5 compiles without problems.

The program below shows the declaration of a Cat class with public member variables.


Accessing the public members of a simple class.

// Demonstrates declaration of a class and
   // definition of an object of the class,
   #include    // for cout

   class Cat                // declare the class object
    public:                 // members which follow are public
      int itsAge;
     int itsWeight;

  void main()
     Cat billo;
     billo.itsAge = 5;    // assign to the member variable
     cout << "billo is a cat who is " ;
     cout << billo.itsAge << " years old.\n";
Output: Billo is a cat who is 5 years old.