When I was compiling the following, I got a error: unknown type name 'ClassA'; did you mean 'ClassB'?
.
I guessed that my compiler needed to know ClassA to know ClassB, but it also needed to know ClassB in order to know ClassA.
So I tried forward declarations (like suggested here).
For instance I declared class ClassA;
before #include "ClassB.hpp"
in my ClassA.hpp. And it worked fine!
But there are still errors in case my classes use embedded classes declaration like right bellow :
error: incomplete type 'ClassA' named in nested name specifier
class ClassA::ClassC;
^~~~~~~~
In this case I tried to declare ClassC
in ClassA
, to use ClassA::ClassC
in ClassB
and to add class ClassA::ClassC;
before #include "ClassB.h"
in ClassA.h (Some of these lines are commented).
But it doesn't do the job.
My files :
I have 5 files :
- ClassA.hpp
- ClassA.cpp
- ClassB.hpp
- ClassB.cpp
- main.cpp
ClassA and ClassB respectivly contain class ClassA
and class ClassA
declarations.
They both include each other.
main.cpp include both ClassA.hpp and ClassB.hpp.
Here is the content of my files :
ClassA.hpp :
#ifndef CLASSA_HPP
# define CLASSA_HPP
class ClassA;
//class ClassA::ClassC; //<----- This doesn't work.
# include "ClassB.hpp"
class ClassA{
public:
// [...]
void printb(ClassB const & b) const;
//class ClassC{
//};
private:
// [...]
};
#endif
ClassA.cpp :
#include "ClassA.hpp"
void printb(ClassB const & b) const{
// [...]
}
ClassB.hpp :
#ifndef CLASSB_HPP
# define CLASSB_HPP
class ClassB;
# include "ClassA.hpp"
class ClassB{
public:
// [...]
void printa(ClassA const & a) const;
// ClassA::ClassC & returnC(ClassA::ClassC elem);
private:
// [...]
};
#endif
ClassB.cpp :
#include "ClassB.hpp"
void printa(ClassA const & a) const{
// [...]
}
main.cpp :
#include "ClassA.hpp"
#include "ClassB.hpp"
int main(void){
ClassA a = ClassA();
ClassB b = ClassB();
a.printb(b);
b.printa(a);
return 0;
}
My question(s) :
In this case, using forward-declarations works for simple classes. But it looks like a workaround to me and it becomes a bit more complicated to use embedded classes and I don't really know how to handle this.
So:
- is there a better way (than forward declatation) to do such things?
- If not, how to do this using forward-declaration with embedded classes like this? What should I do instead of forward declaring
class ClassA::ClassC
?