Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21976

Apparent encapsulation

The new command allocates memory in the heap to store an object. Static allocation may cause the object to be put on the stack instead. But they're both not protected area of memory. I can access to this, which is just the address of the object, and then use the indirection operator, so pointing to the object fields:

string str=string("hello");
void** str_this=(void**)&str;
char* str_data= (char*)*str_this;
str_data[0]='s';
str_data[1]=0;
cout <<str_data; // prints "sello"

So is this still considered encapsulation? Is charge of the class user (who instantiates the object) to avoid poiting to it's data?

Upvotes: 0

Views: 104

Answers (3)

mcmcc
mcmcc

Reputation: 842

C++ is a powerful language. With great power comes great responsibility, as a comic book superhero once said.

Once you cast an object pointer to void* and then recast that pointer to another type, in this case char*, you have entered into the land of undefined behavior. The language makes no guarantees about what will and what will not work if you try to use that char* pointer. It is only legal to recast the void* back to the original type (string*).

Invoking undefined behavior is not a legitimate way of breaking encapsulation, because once you cross that undefined behavior threshold, anything is possible (just not portable).

Upvotes: 3

Random Wombat
Random Wombat

Reputation: 116

Your code implicitly relies on a particular implementation of std::string. In other words, your code is breaking the encapsulation of std::string. Worse yet, it invokes undefined behavior, so it may work, or it may not, or it may crash...

Upvotes: 2

Joachim Isaksson
Joachim Isaksson

Reputation: 180947

Encapsulation in programming does not usually mean "impossible to work around if you really really try".

It usually means closer to "being able to make a clear distinction what is supposed to be exposed or not and not have things accidentally exposed or used".

I don't think anyone will mistake your code for accessing a string the way it's supposed to be accessed.

Upvotes: 6

Related Questions