C++03 Resolve a circle composition when calling a member function

100 views Asked by At

I've got the following class structure. This obviously won't compile. I can forward declare B. Then, I can either use function pointers in function calls but it's not a nice solution, as I would call other other functions in A from A::funcA or put part of the declaration of B into a header, which would be a few hundreds of lines and would be practical.

What (else) would be the preferred way to handle this situation?

class B;

class A
{
public:
    void funcA(B* b);
    double funcA2();
    int funcA4(B* b);

private:
    E memberA1;
    E memberA2;
};

void A::funcA( B* b) {
    b->funcB(a->memberA1, a->memberA2);

class B : public BBase
{
public:
    void FuncB(E* e1, E* e2)
    {
        /* using const objects of B that are initialized 
           by B() and some other functions... */
    }

    std::vector<C*> memberB1;             // C has std::vector<A*> memberC1
};

int main() {
    calling B->memberB1.at(0)->memberC1.at(0)->funcA();
}

I have the the following (omitting some unneccesary lines):

A.h

Class B;

Class A {
    declaration of A
};

A.cpp ....

B.h

#include "A.h"
#include "BBase.h"

Class B {
    declaration of B
};

B.cpp ....

BBase.h

#include "C.h"
#include "A.h"
#include "AInterface.h"

typedef std::vector<AInterface> AList;

BBase {
   declaration of abstract BBase
};

BBase.cpp ....`

But I still get error: member access into incomplete type 'B'.

2

There are 2 answers

0
Some programmer dude On

Assuming E and C are adequately declared/defined, then what you have is almost fine. The problem is that you define the member function of A before you have the definition of the B class, make sure that class B is fully defined (the actual class, not the full implementation of its member functions) before you you have the A member functions implemented.

So something like this:

class B;

class A { ...; void member_function(B*); ... };

class B { ...; void other_member_function(); ... };

void A::member_function(B* b) { ...; b->other_member_function(); ... }
2
AlexTheo On

I would suggest to use either the Interface instead of concrete B class

class B : public IB{
};

and pass IB instead of B to A.

either even better in c++ use a template function and bind your member function which you want to call

a.funcA( std::bind( &B::funcB, &b, someArg );