Answer the question
In order to leave comments, you need to log in
How to access fields and methods of an unknown object?
Let's say there is a situation.
Class A has two nested sheets, one for objects of class B, the second for objects of class C.
Now object A can fully control them. But objects B and C don't know anything about each other.
Accordingly, in order for, say, the field of object B to assign data from the field of object C, we need to go down to object A,
only there we can implement such a method.
Is it possible to provide data exchange between B and C at their own level?
Answer the question
In order to leave comments, you need to log in
This means: an object of class B must have (or not have) a “comrade” of class C. Not owned, but by reference. And better not class C, but its subset, implemented as an interface (I called it IC). On A, we generally cheer - his task is to assemble B and C in the right form, and that's it.
See the Dependency Injection design pattern.
class IC { // interface
public:
virtual int getC() = 0;
virtual ~IC() = default;
};
class C : public IC {
public:
int getC() final { return 42; }
};
class B {
public:
IC* buddy() const { return fBuddy; }
void setBuddy(IC* aBuddy) { fBuddy = aBuddy; }
void someJob() const { if (fBuddy) std::cout << fBuddy->getC() << std::endl; }
private:
IC* fBuddy = nullptr;
};
class A {
public:
A() { b.setBuddy(&c); }
private:
C c;
B b;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question