The program consists of 5 files: "a.cpp", "ah", "b.cpp", "bh", "main.cpp".

Halyards with h extensions contain class declarations. In files with the cpp extension, the implementation of class methods.

The build is as follows: g ++ main.cpp a.cpp b.cpp

The contents of the file "ah"

class A { public: void anyfunc(); };

Contents of the file "a.cpp"

void A::anyfunc() { func(); }

File Contents "bh"

#include "ah" class B { public: void func(); private: A obj; };

Contents of the file "b.cpp"

void B::func() { // ... }

It is necessary that the member functions of class A have access to the function members of class B. But, with this code, the compiler will of course generate an error. Both classes must have access to func (), parent B and A. At the same time, class A must be declared before class B in order to be able to declare A obj in class B. I think the problem would be resolved by class A is from B (class A: public B), but for the above reasons, this is not possible.

  • Interestingly, I didn’t understand anything ...? - AR Hovsepyan
  • one
    The question is not clear. Access to the functions of class B is possible only through an object of class B What class B object were you going to access the functions of class B ? Why do you call class B "parent"? I do not see any inheritance in your code. - AnT pm
  • As I understand it, you need to include bh in the a.cpp implementation file, no? Show how you want to access functions B - hopefully not through a member of B obj in class A ? :) - Harry
  • I apologize, I have poorly formulated the problem, I have already fixed it - elo2cx
  • Not understood. That is, you completely reworked the question after you received the answer ??? - AnT

1 answer 1

My crystal ball tells you that you need something like this.

 // Ah class B; class A { B *b; public: A(B *b) : b(b) {} void anyfunc(); }; 

 // Bh #include "ah" class B { public: B() : obj(this) {} void func(); private: A obj; }; 

 // A.cpp #include "bh" void A::anyfunc() { b->func(); } 

You can access the "enveloping" B from the "nested" A without passing the pointer, but through a technique like container_of , but I don’t want to do this hacking in C ++ code.

  • In our regular rubric "More fiend, for example," you can also use B(): obj([this](){ func(); }) {} , as an option. Then, at least, A does not need knowledge about B - bipll pm
  • Such an error appeared /tmp/ccQ5cYF2.o: In function A::anyfunc()': a.cpp:(.text+0x17): undefined reference to - elo2cx
  • @ elo2cx and you implemented it? Taurus wrote? - Alexander Chernin
  • one
    Thank you, the body of the function wrote, the error disappeared. I designed the program incorrectly, that is why there was such an incorrect question - elo2cx pm