Access-specifiers are not foolproof?

Posted by Nawaz on Stack Overflow See other posts from Stack Overflow or by Nawaz
Published on 2010-12-26T08:55:12Z Indexed on 2010/12/26 9:54 UTC
Read the original article Hit count: 232

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about macros