Access Functions vs. Public Data Members

Writing access functions might seem like a lot of needless work. You may argue that it's much simpler to declare the data members as public and manipulate them directly. After all, why call a setMonth and getMonth function when you could simply access the month member itself?

The advantages of access functions become apparent when we recall the example of the date structure defined in C. Access functions ensure that your objects never contain invalid values. You can always be sure that you can display the contents of a Date object without printing out nonsense.

More importantly, access functions let you change the implementation of your class easily. For example, remember the scenario in which you decide to encode the month and day within the bits of a single integer in order to save space. In C, you have to modify every program that uses date structures. This could involve thousands of lines of code.

In C++, however, all you have to rewrite are the class's member functions, which constitute far fewer lines. This change has no effect on any programs that use your Date class. They can still call getMonth and setMonth, just as they did before. The use of access functions instead of public members saves you a huge amount of rewriting.

By using member functions to control access to private data, you hide the representation of your class. Access functions let you change the implementation of a class without affecting any of the programs that use it. This convention is known as “encapsulation,” which is one of the most important principles of object-oriented programming. Encapsulation is discussed in more detail in Chapter 9, “Fundamentals of Object-Oriented Design.”