If I’ve a class like this,
class Sample
{
private:
int X;
};
Then we cannot access X from outside, so this is illegal,
Sample s;
s.X = 10; // error - private access
But we can make it accessible without editing the class! All we need to do is this,
#define private public //note this define!
class Sample
{
private:
int X;
};
//outside code
Sample s;
s.X = 10; //no error!
Working code at ideone : http://www.ideone.com/FaGpZ
That means, we can change the access-specifiers by defining such macros just before the class definition, or before #include <headerfile.h>,
#define public private //make public private
//or
#define protected private //make protected private
//or
#define so on
Isn’t it a problem with C++ (Macros/access-specifiers/whatever)?
Anyway, the point of this topic is:
Using macros, we can easily violate encapsulation. Access-specifiers are not foolproof! Am I right?
Technically, all you’ve shown is that “we can turn a legal program into Undefined Behavior” without editing one specific class.
That’s hardly news. You can also turn it into undefined behavior just by adding a line such as this to the end of
main():Access specifiers in C++ are not a security feature They do not safeguard against hacking attempts, and they do not safeguard against people willfully trying to introduce bugs into you code.
They simply allow the compiler to help you maintain certain class invariants. They allow the compiler to inform you if you accidentally try to access a private member as if it were public. All you’ve shown is that “if I specifically try to break my program, I can”. That, hopefully, should be a surprise to absolutely no one.
As @Gman said, redefining keywords in the C++ language is undefined behavior. It may seem to work on your compiler, but it is no longer a well-defined C++ program, and the compiler could in principle do anything it likes.