copy/assignment/move constructors and private data

Started by
3 comments, last by Ryan_001 9 years, 11 months ago

Hi

Let's say we have class A and class B that both have private data and are very different from each other.

We want to implement copy/assignment/move constructors for both classes such that A can be constructed with private data from B and vice versa.

Do we have to invoke the friend keyword in order for these constructors to get access to the private data?

Advertisement


Do we have to invoke the friend keyword in order for these constructors to get access to the private data?

If you dont have any public interface (eg public getter) and the target class is not a specialisation of the source class (in this case you could copy the protected variables), only using friend comes to mind.

But... keep in mind the need to grab the private parts of another object is a code smell very indicative of poor design. You might want to re-think the single purpose of your class(es) or their interface(s) before your project grows much more.

Stephen M. Webb
Professional Free Software Developer

I agree with Bregma. Why is it that A can access B's private data in ways that other parts of the code can't? Perhaps the interface of B is incomplete?

Also, you will get much better answers if instead of "A" and "B" you tell us what the actual names of the classes are, so we can get an idea of why one would need to know the details of the other. We might be able to propose a better design too.

There are times when its necessary for a class to access the internals of another... Its not necessarily a bad design decision.

This topic is closed to new replies.

Advertisement