(★★★) Making Member Data Private

Posted: March 9, 2011 in C++

Let’s see some coding first.

#include <iostream>

class Cat
        int itsAge;
         int itsWeight;

void main()
        Cat Frisky;
        Frisky.itsAge = 5;
        std::cout<<“Frisky is a cat who is “<<Frisky.itsAge<<” years old.”<<std::endl;

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 acess information about the class. For example, if itsAge is private, how would you be able to set or get a Cat object’s age?

To acess private data in a class, you must create public functions known as accessor methods. Use these methods to set and get the private member variables. These accessor methods are the member functions that other parts of your program call to get and set your private member variables.

A public accessor method is a class member function used either to read (get) the value of a private class member variable or to set its value.

Why bother with this extra level of indirect acess? Why add extra functions when it is simpler and easier to use the data directly? Why work through accessor functions?

The answer to these questions is that accessor funtions enable you to seperate the details of how the data is stored from how it is used. By using accessor functions, you can later change how the data is stored without having to rewrite any of the other functions in your programs that use the data.

If a funtion that needs to know a Cat’s age access itsAge directly, that function would need to be rewriten if you, as the author of the Cat class, decided to change how that data is stored. By having the function call GetAge( ), you Cat class can easily return the right value no matter how you arrive at the age. The calling function doesn’t need to know whether you are storing it as an unsigned integer or a long, or whether you are computing it as needed.

This technique makes your program easier to maintain. It gives your code a longer life because design change don’t make your program obsolete.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s