Is this a suitable use of class friendship?

When creating Windows parent and child dialog classes, it is usually recommended that you create a child class by another parent class to access its personal data or use access functions?

+4
source share
3 answers

The need for another is rarely met - usually this is when you need to redefine some deep behavior in one class without rewriting it so that they both inherit from the same base or do not provide many accessories.

The only time I needed was to rewrite the rendering of openGL rendering in ActiveX - when I needed to get a lot of low-level model data, but was unable (for non-technical reasons) to override the general ABC.

+3
source

I had a similar situation lately, when I wanted to set up some private member variables of class A to class B.

I did not want to add public access functions because it could bring these members to all other classes.

I did not want B to be a friend of A because it would expose all private members from A to B.

So, I made another class (private A-to-B interface) solely for this purpose. This is friend A, and it has nothing but access functions:

class A { int top_secret; // only A has access to it int secret; // only A and B have access to it friend struct AToBInterface; }; struct AToBInterface { static int secret(const A& object) {return object.secret;} }; class B { void DoSecretStuff(A& object) { int secret = AToBInterface::secret(object); ... } }; 

You can customize the syntax (for example, if you need read and write access), this is just an idea. I use it only in one place in the code, so there is no problem if the syntax is a little hairy.

+2
source

IMHO, almost never.

"friend" is often used to break encapsulation, as it allows an external object to access the personal data of your class. You almost never want to do this - it is often better / safer to expose “semi-private” data through public accessors (which can validate) than expose personal information to another class (which can thrombose on you).

However, sometimes you will have a couple / group of very closely related classes, where it makes sense to keep them as separate classes, but they need low-level access to data that really should not be shared with the world as a whole. This is where a "friend" can be used - with caution.

As a general rule, try to limit the amount of friends (for example, friend methods, not friend classes) to minimize areas where direct access to sensitive data is allowed. Remember, another programmer reading your code might think that “private” means that the data is really confidential and can be confused by friends. In addition, the more friends you use, the harder and harder it is to maintain your design. They may be useful, but make sure you have a good rationale for each use.

0
source

Source: https://habr.com/ru/post/1337036/


All Articles