C++ Programming Guide

Classes and Data Abstraction

If you are a C programmer, think of a class as an extension of the struct type. A struct contains predefined data types, for example, char or int, and might also contain other struct types. C++ allows a struct type to have not only data types to store data, but also operations to manipulate the data. The C++ keyword class is analogous to struct in C. As a matter of style, many programmers use struct to mean a C-compatible struct type, and class to mean a struct type that has C++ features not available in C.

C++ provides classes as a means for data abstraction. You decide what types (classes) you want for your program data and then decide what operations each type needs. In other words, a C++ class is a user-defined data type.

For example, if you define a class BigNum, which implements arithmetic for very large integers, you can define the + operator so that it has a meaning when used with objects in the class BigNum. If, in the following expression, n1 and n2 are objects of the type BigNum, then the expression has a value determined by your definition of + for BigNum.


n1 + n2

In the absence of an operator +() that you define, the + operation would not be allowed on a class type. The + operator is predefined only for the built-in numeric types such as int, long, or float. Operators with such extra definitions are called overloaded operators.

The data storage elements in a C++ class are called data members. The operations in a C++ class include both functions and overloaded, built-in operators (special kinds of functions). A class's functions can be member functions (declared as part of the class), or nonmember functions (declared outside the class). Member functions exist to operate on members of the class. Nonmember functions must be declared friend functions if they need to access private or protected members of the class directly.

You can specify the level of access for a class member using the public, private, and protected member access specifiers. Public members are available to all functions in the program. Private members are available only to member functions and friend functions of the class. Protected members are available only to members and friends of the base class and members and friends of derived classes. You can apply the same access specifiers to base classes, limiting access to all members of the affected base class.