Access to the class method in the implementation class

I have a class, suppose a.cpp . In private ownership of this class, I have a pointer to b.cpp and c.cpp , where b.cpp is the implementation of the virtual interface class, which allows you to call d.cpp . Also, in private ownership of c.cpp , I have a pointer to an interface class, d.cpp .

I want to access one of the methods of the a.cpp class in the b.cpp class. How can i do this?

The example may be ok, let me give some methods in classes

 class A{ private: B *_classB; C *_classC; public: int add(int, int); } 

Now the class of the interface D So, in the class D we have

 class D{ public: virtual int mul(int, int) = 0; } 

Now class B is an implementation of the interface class D So, B looks like this:

 class B{ private: int first_num; int second_num; public: virtual int mul(int a, int b); } 

and class C also has a pointer to an interface class, so C looks like

 class C{ private: D *_classD; } 

Now I want to call the int add (int, int) method in class B.

+4
source share
3 answers

Since A contains B and there is no other relationship, you will need to keep a pointer to the owner of A in class B

+1
source

You need an instance of class A , or you need to make add static member function of A

In other words, the static solution would be something like this:

 class A { ... static int add(int, int); }; 

Then the call will appear:

 ... A::add(x, y); ... 

Or:

 class B{ private: int first_num; int second_num; public: virtual int mul(int a, int b); int add(const A& a, int x, int y) { return a.add(x, y); } } 

From a function to, it will look something like this:

 void A::func(int x, int y) { b->add(*this, x, y); } 

There are several other solutions. But without additional information about what your actual use case is, it will probably be as good as it gets.

+1
source

You can make an object of type A a member of the data from B, or you can make the pointer A a member of the data B. Since the classes you created have no relationship between A and B. If you do not want to do inheritance, which, I think, is not a problem here.

0
source

Source: https://habr.com/ru/post/1496614/


All Articles