Safety of Implementation
It’s one thing to create a language that prevents you from shooting yourself in the foot; it’s quite another to create one that prevents others from shooting you in the foot.
Encapsulation is the concept of hiding data and behavior within a class; it’s an important part of object-oriented design. It helps you write clean, modular software. In most languages, however, the visibility of data items is simply part of the relationship between the programmer and the compiler. It’s a matter of semantics, not an assertion about the actual security of the data in the context of the running program’s environment.
When Bjarne Stroustrup chose the keyword private to designate
hidden members of classes in C++, he was probably thinking about shielding
a developer from the messy details of another developer’s code, not the
issues of shielding that developer’s classes and objects from attack by
someone else’s viruses and Trojan horses. Arbitrary casting and pointer
arithmetic in C or C++ make it trivial to violate access permissions on
classes without breaking the rules of the language. Consider the following
code:
// C++ codeclassFinances{private:charcreditCardNumber[16];...};main(){Financesfinances;// Forge a pointer to peek inside the classchar*cardno=(char*)&finances;printf("Card Number = %.16s\n",cardno);}
In this little C++ drama, we have written some code that violates
the encapsulation of the Finances class and pulls out some secret information. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access