I have a problem with recursive imports in C++. I have this 2 classes:

//File A.h
#include "B.h"

class A{
        public:		 
		A(){};

		void doA(B b){ b.doB(); }
}
//File B.h
#include "A.h"

class B{
	public:		 
		B(){};

		void doB(A a){ a.doA(); }
}

I tried to use forward declarations but it doesn't work because i call methods "doA" and "doB" so I cant use forward declarations.

Do someone know what can I do to compile it?

Thank you!

Are you macro protecting your header files?

#ifndef _SOME_HEADER
#define _SOME_HEADER
class SomeClass{...};
#endif

or

#pragma once
class SomeClass{...};

Yes, I have

#ifndef _SOME_HEADER
#define _SOME_HEADER
....
#endif

in all my classes.

What i dont undestand is why i can't find a solution in the web, because i think it's a very common problem....

What's the compiler error look like?

the problem is the chicken and the egg paradox. what comes first in your code A or B?. if A is first and A uses B then the compiler goes to B to find out what B is but B has A in it and A isn't finished so it doesn't know what A is yet either. the same thing will happen if B is first. unfortunately there is no solution for this problem. it just isn't possible in c++ right now. you can have A have a B as long as B doesn't have an A in it or the other way around with B but A cant have B when B has A in it. i really hope I'm making sense

Thank you, but i have just solved the problem.
I used forward references in A.h and B.h, and used includes in A.cpp and B.cpp

I don't know if this is standard C, but in C++ Builder works.

//File A.h
#include "B.h"

class B;            // pre-declare B class
class A {
public:		 
    A(){};
    void doA(B b){ b.doB(); }
}
//File B.h
#include "A.h"

class A;             // pre-declare A class
class B {
public:		 
    B(){};
    void doB(A a){ a.doA(); }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.