PRIVATE MEMBERS OF A CLASS

Having a constructor that sets the values of the data members of a class object, but still admits the possibility of any part of a program being able to mess with what are essentially the guts of an object, is almost a contradiction in terms. To draw an analogy, after you have arranged for a brilliant surgeon whose skills were honed over years of training to do things to your insides with a sharp knife, letting the local plumber or bricklayer have a go is a bit risky. You need some protection for your class data members.

You can get the security you need by using the private keyword when you define the class members. Data and function members of a class that are private can, in general, be accessed only by member functions of a class. There’s one exception, but we’ll worry about that later. A normal function has no direct means of accessing the private members of a class. This is shown in Figure 7-6.

Having the possibility of specifying class members as private also enables you to separate the interface to the class from its internal implementation. The interface to a class is composed of the public data members and the public member functions, in particular, because they can provide indirect access to all the members of a class, including the private members. By keeping the internals of a class private, you can later modify them to improve ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.