Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-specifiers are not foolproof?

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?

like image 479
Nawaz Avatar asked Jan 26 '26 02:01

Nawaz


1 Answers

First of all, it's illegal to do that. private is a keyword, and you can't use it as an identifier in a macro; your program would be ill-formed.

But in any case, it's not a problem with macro's at all. It's with the fool who used them in a silly manner. :) (They're there to help you be safe, they're not there to help you be safe and block all access to them no matter what you try. C++ protects against Murphy, not Machiavelli.)

Note that you can access privates in a well-formed and well-defined manner, as demonstrated here. Again, this isn't a problem with the language, it's just not the job of the language to do more than necessary to keep prying hands out.

like image 118
GManNickG Avatar answered Jan 28 '26 15:01

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!