In C++ let's say I have some class A:
Class A
{
int a1, a2, a3;
void foo();
}
and I need to use a subset of members (a1, a2) in a member function for a second class B.
What I'm wondering is whether I should define the arguments of B's member function by passing a pointer to A as an argument, or whether I should pass the members of A as arguments. e.g.,
Class B
{
int b1, b2;
void bar(A &a);
}
or should this be
Class B
{
int b1, b2;
void bar(int a1, int a2);
}
The latter would seem to minimize having to violate encapsulation, because B can then be largely agnostic about the constituents of A; whereas, in the former case, B would have to know something about the members of A. So it would seem the second implementation would be preferable.
Another reason the first implementation seems problematic to me is that, ideally, I'd like to keep the members (a1, a2, a3) of A protected rather than public. Normally I'd be tempted to make B a friend class of A, but the problem here is that A and B will both each have several derived classes, and since friendship doesn't inherit in C++ that wouldn't seem to be a good solution.
So these reasons would argue for using something like the second definition of B. However, in the actual code I'm dealing with, there are quite a few (about 6 or more) members of A that B will require, so this could get unwieldy. Being able to just pass a pointer to A would seem preferable from a readability standpoint and hide the details of what B.bar() requires from other parts of the code that deal with B.
Perhaps one work around would be to have methods inside A that do something like:A::get_a1() {return this->a1}
or something, but I'm also not sure if that's really the correct design solution here.
A
hold an instance ofB
instead ofa1
anda2
individually? So you'd basically refactor both members to a single one that is an instance ofB
?