Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Do friends violate encapsulation?

encapsulation friends violate
0
10 Posted

Do friends violate encapsulation?

0

No! If they’re used properly, they enhance encapsulation. You often need to split a class in half when the two halves will have different numbers of instances or different lifetimes. In these cases, the two halves usually need direct access to each other (the two halves used to be in the same class, so you haven’t increased the amount of code that needs direct access to a data structure; you’ve simply reshuffled the code into two classes instead of one). The safest way to implement this is to make the two halves friends of each other. If you use friends like just described, you’ll keep private things private. People who don’t understand this often make naive efforts to avoid using friendship in situations like the above, and often they actually destroy encapsulation. They either use public data (grotesque!

0

If they’re used properly, they actually enhance encapsulation. You often need to split a class in half when the two halves will have different numbers of instances or different lifetimes. In these cases, the two halves usually need direct access to each other (the two halves used to be in the same class, so you haven’t increased the amount of code that needs direct access to a data structure; you’ve simply reshuffled the code into two classes instead of one). The safest way to implement this is to make the two halves friends of each other. If you use friends like just described, you’ll keep private things private. People who don’t understand this often make naive efforts to avoid using friendship in situations like the above, and often they actually destroy encapsulation. They either use public data (grotesque!), or they make the data accessible between the halves via public get() and set() member functions. Having a public get() and set() member function for a private datum is OK only

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.