0

I'm trying to achieve a thing. My requirements are C++03 and no external libraries.

I have objects of two different classes, and I'd like them to be able to communicate. My first attempt had each class hold a pointer to the other, and use the pointer to call a member function when some condition is met

class A;
class B;

class A
{
public:
    void foo();
    void notify();
    B* partner;
};

class B
{
public:
    void bar();
    void notify();
    A* partner; 
}

void A::foo()
{
    partner->notify();
}

void B::bar()
{
    partner->notify();
}

The problem for me was in my actual example, A and B were in different source files, and the now A.h includes B.h and vise versa. My thought is I can't just omit the includes and do a forward declare of the class because A needs not only to know about B, but about B's member function as well.

What's a clean and simple way to do this?

edit: In the question linked, the two classes were not calling each other's member functions, so a forward declare of the classes were sufficient. I'd like to be able to call each other's member functions (or have someone suggest a different way of passing information between the two objects)

user2864293
  • 380
  • 2
  • 10
  • ***I'd like to be able to call each other's member functions*** That is not an issue with the linked question. Make sure you define your functions in the source files not the headers. – drescherjm Feb 06 '17 at 19:50
  • How is it not an issue? I want A to do more than just hold a pointer to B, I want A to be able to call one of B's member functions through that pointer. If I only forward declare the class, then A won't know about B's member functions. – user2864293 Feb 07 '17 at 01:24
  • 1
    It will in the source file for A. There you include the header for class B. – drescherjm Feb 07 '17 at 13:51
  • 2
    @user2864293 Simply forward declare `class A` in B's header, `class B` in A's header and then include both headers in both source files. – François Andrieux Feb 07 '17 at 14:24
  • Split your code into the actual .h and .c files. – CL. Feb 07 '17 at 14:32

0 Answers0