tags:

views:

160

answers:

5

How can I Violate Encapsulation property without having a compile time error? (in C++)

just so curious..

This was actually a question asked by one of my professor.. Please don't misunderstand. This was asked when we had a discussion over compiler error's

+2  A: 

You don't get to*. Encapsulation is a feature of C++.

*unless you do something dark, evil, and magic.

Robert P
@Robert again i m not into dark, evil thing.. This was a question asked by our professor in college. I was damn sure that it cannot be done.
Nagaraj Tantri
See [FredOverflow's answer.](http://stackoverflow.com/questions/3002101/how-can-i-violate-encapsulation-property/3004223#3004223) His is the manifestation of this evil. :)
Robert P
Also, see [evil: adj. (from the Jargon file.)](http://catb.org/jargon/html/E/evil.html)
Robert P
+1  A: 

You change the headers defining the classes in question to make the desired members public. In other words, you remove the encapsulation. Don't do this.

Novelocrat
+5  A: 
#define private public
#define protected public
#define class struct

There you go :-)

FredOverflow
`template <class T> T youBrokeIt(const T }`
KennyTM
This is awesome. +1
egarcia
@ega: Actually, that was intended as a joke. Why would anyone WANT to do this? Encapsulation is a good thing! If you really need to touch private parts, then your design is flawed, and you must refactor.
FredOverflow
I meant it was an awesome joke! I would not even _dream_ to define private as public.
egarcia
Ooh, you win it. A proper manifestation of evil if I've ever seen one. Except...what about protected? :)
Robert P
@Rob Thanks for reminding me about `protected` :)
FredOverflow
Ok. Now we need to burn it with fire.
Robert P
+2  A: 

I'm going to assume that by "violating encapsulation" you mean "accessing private members from outside a class".

The only way to do this "legally" that I know is using friend classes / methods.

However, in order to use them you will need to modify the class which has private members - at which point it might be simpler to just redefine some methods from private to protected or public, depending on the case.

egarcia
friends do not break encapsulation, because you get to choose who your friends are. It's not like somebody could become your friend without your consent.
FredOverflow
please see my first phrase - I'm defining "encapsulation" as "not being able to access private members from outside". It is not a "standard" or "complete" definition, but I suspect it is the one the OP is using on his question.
egarcia
A: 

Design a mirror class that has the same members as the class you are trying to access the nonpublic members of and hardcast an object of said class to the mirror class.

class original
{
  private: int x,y,z;
  public: int dosomething();
};

class mirror
{
  public: int x,y,z;
};

int main()
{
  original *o = new original;
  mirror *m = (mirror*)o;
  m->x = 10;
}

this of course is not guaranteed to work.

Ozan