Sign in to follow this  
lantianman

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

Recommended Posts

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; }

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this