1.11M Members

Problem with recursive includes

 
0
 

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!

 
0
 

Are you macro protecting your header files?

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

or

#pragma once
class SomeClass{...};
 
0
 

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....

 
0
 

What's the compiler error look like?

 
0
 

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

 
0
 

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

Question Answered as of 4 Years Ago by dusktreader and NathanOliver
 
0
 

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(); }
}
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: