In C, encapsulation was accomplished by making things
staticin a compilation unit or module. This prevented another module from accessing the
staticstuff. (By the way,
staticdata at file-scope is now deprecated in C++: don’t do that.)
Unfortunately this approach doesn’t support multiple instances of the data, since there is no direct support for making multiple instances of a module’s
staticdata. If multiple instances were needed in C, programmers typically used a
struct. But unfortunately C
structs don’t support encapsulation. This exacerbates the tradeoff between safety (information hiding) and usability (multiple instances).
In C++, you can have both multiple instances and encapsulation via a class. The
publicpart of a class contains the class’s interface, which normally consists of the class’s
publicmember functions and its
protectedparts of a class contain the class’s implementation, which is typically where the data lives.
The end result is like an “encapsulated
struct.” This reduces the tradeoff between safety (information hiding) and usability (multiple instances).