N
N
Nikita Azarchenkov2017-03-09 15:40:16
Programming
Nikita Azarchenkov, 2017-03-09 15:40:16

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

1 answer(s)
M
Mercury13, 2017-03-09
@Mercury13

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;
}

Especially for those who are in C++: in this form, A is not relocatable because of the c.fBuddy pointer. There are many ways to fix this - for example, fix the copy constructor and the "assign" operation of class A.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question