Is it possible to declare two classes and call each other's functions?

Started by
4 comments, last by Ravuya 17 years, 7 months ago
The following code failed to compile because I cannot call b->check() from A. Is there any way to do it? Thanks! class B; class A { public: void fA(B* b) { b->check(); } void check() { cout<<"This is A."<<endl; } }; class B { public: void fB(A* a) { a->check(); } void check() { cout<<"This is B."<<endl; } }; int main(void) { A a; B b; a.fA(&b); b.fB(&a); getchar(); return 0; }
Advertisement
Can you repost the code in source tags? It will make it easier to read. Also, post the compiler errors.
Put the definition of one of the member functions in a source file. You can't call a member function on something that you only have a forward declaration for.
Certainly. However, you will have to place your implementation of the classes in seperate source files.

In order to call B::check from A::fA(), the compiler must have seen the definition of B. Likewise, in order to call A::check from B::fB(), the compiler must have seen the definition of A. A forward declaration is just a declaration, not a definition.

The only way you can have this work is to place the definition of A's member functions in their own file (say, A.cpp) and those of B in their own file (say, B.cpp). Both of the .cpp files can #include "A.h" and "B.h" (but A.h and B.h should only provide forward-declarations of B and A, respectively, and not try to include their headers).

The better solution, however, is probably to avoid having a design that leads you to require circular dependancies among classes.
Got it! Thank your for your help!
Circular dependencies generally indicate poor design. They're bug-prone, difficult to debug, and complex to maintain.

You should definitely try to see if you can refactor it out somehow; you'll run into lots of trouble, particularly when it comes time to clear memory or have other people maintain your code.

This topic is closed to new replies.

Advertisement