For example,
class B {
int* b1;
int* b2;
B(int* x, int* y) {
b1 = x;
b2 = y;
}
};
class A {
int* a1;
int* a2;
B* b1;
public:
A() {
a1 = new int;
a2 = new int;
b1 = new B1(a1, b1);
}
};
I want to access values pointed by a1 and a2 from objects of both class A & B. Where i should write function for the same, so that this function can be called by objects of A and objects of B. ?
In this special context, you are only passing pointers so the objects pointed by a1
and a2
are the objects pointed by b1
and b2
. On the other hand, an A
object knows what B
it contains, but an instance of B
has no knowledge about being contained in an A
.
Because of that, I think that the function manipulating the pointed objects should be declared in B
class. Then if the existence of B is member of the public API of A (with a getter for example) it is enough:
class B {
...
void do_something(...) {
// do something with objects pointed by b1 and b2
}
};
...
A a;
a.getB()->do_something();
...
If the B
member of A
is an implementation detail, you should declare a relay method in A:
class A {
...
void do_something(...) { // delegate to the `B` member
b1->do_something(...);
}
};
...
A a;
a.do_something(...);
...