Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ever a good idea to break encapsulation?

I am just starting to learn about encapsulation, and I stumbled upon two functions used by std::string that seems to break its encapsulation.

Regarding c_str() and data() from http://www.cplusplus.com/reference/string/string/c_str/ and http://www.cplusplus.com/reference/string/string/data/

"The pointer returned points to the internal array currently used by the string object to store the characters that conform its value".

For someone just learning about OO programming, is it ever a good idea to break encapsulation? How about for someone who is more advanced?

As an aside, it seems like this is different behavior from C++98. Why do you believe that they made these changes?

Thanks for your time.

like image 451
Matthew Papageorge Avatar asked Mar 18 '23 05:03

Matthew Papageorge


1 Answers

While sometimes utility and backwards compatibility overrides the desire for encapsulation like Mahmoud mentions don't let the C++ standard library be validation for breaking encapsulation lightly. This particular point has been contentious and even a source of bugs within many code bases. The problem with c_str is that it opens up bad memory corruption by people abusing the returned pointer value or holding on to it for too long after modifying the string which is considered undefined behavior, but neither the compiler nor the runtime environment can enforce that restriction, so in this case the C++ committee chose convenience over safety, and that tradeoff should not be made without considerable justification.

like image 65
b4hand Avatar answered Apr 01 '23 21:04

b4hand