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?
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.