The C language provides only a few simple data structures, so that implementing complex data structures usually means defining a C struct and some functions to operate on it. Unfortunately, the actual data structure and the functions for manipulating it seldom have any obvious or binding connection, except perhaps a naming scheme and placement in the same C module.
C++ is richer in data structures, primarily by supplying classes ¾ which define real types. A class is a language-supported means of encapsulating both the data and the functions for accessing it within a single well-defined object. The encapsulation is real, too; by using the public, private, and protected access specifiers, you can completely control all access to the data.
The most important way to leverage C++ classes for data structures is to encapsulate the structures themselves inside classes, along with the functions to manipulate the structures. For example, SHOWDIB.H declares a group of functions for operating on a DIB: OpenDIB, WriteDIB, DibNumColors, and so on. MFC's class CBitmap supports ordinary bitmaps, not DIBs, but you could write a class CDIB, embedding a handle to a DIB and encapsulating the loose functions now declared in SHOWDIB.H.
Class encapsulation also lets you clean up your header files in a variety of ways, such as encapsulating loose collections of global variables or #define directives inside a class. For example, SHOWDIB defines the following flags in SHOWDIB.H for its FileOpen function (comments removed):
#define OF_MUSTEXIST 0x00010000 #define OF_NOSHOWSPEC 0x00020000 #define OF_SHOWSPEC 0x00000000 #define OF_SAVE 0x00040000 #define OF_OPEN 0x00080000 #define OF_NOOPTIONS 0x00100000
In C++, you might declare an enumerated type (with more readable mixed-case names) within the scope of a file-handling class, perhaps derived from the MFC CFile class:
class CMyFileClass : public CFile
{
...
enum FileFlags
{
MustExist = 0x00010000 // file must exist if user hits Ok
NoShowSpec = 0x00020000 // DO NOT Show search spec in edit box
ShowSpec = 0x00000000 // Show search spec in edit box
Save = 0x00040000 // Ok button will say "Save"
Open = 0x00080000 // Ok button will say "Open"
NoOptions = 0x00100000 // Disable the options fold out
};
// ...
};
From outside the class, when you pass file flags as function arguments, you specify the encapsulated flag name with a qualifier:
OpenFile( ..., CMyFileClass::ShowSpec, ... );