I’ve created a class A and a Class B, and I’m trying to set a vector of type B in A, and a vector of type A in B:
class A Header:
#ifndef A_H_
#define A_H_
#include "B.h"
#include <vector>
using namespace std;
class A {
public:
vector<B> bvector; // here is the error
A();
};
#endif /* A_H_ */
class B header:
#ifndef B_H_
#define B_H_
#include "A.h"
#include <vector>
using namespace std;
class B {
vector<A> aVector; //Here is the error
public:
B();
};
#endif /* B_H_ */
But I get the following errors:
"..\src/B.h:16:8: error: ‘A’ was not declared in this scope
..\src/B.h:16:9: error: template argument 1 is invalid
..\src/B.h:16:9: error: template argument 2 is invalid"
Which flips to A.h if I delete the bad line in B. What am I doing wrong?
You are creating a circular dependency between your classes. This is generally a bad thing, particularly in C++.
The compiler, in order to compile A, needs to know the definition of B (#include “B.h”). Unfortunately the B header contains a reference to A class (here’s the circular reference).
The compiler can’t handle this situation, since A header is already included in the current TU (see include guards).
Despite the fact that often having circular references is a symptom of a bad design, you can eventually overcome the problem using forward declaration.
For example you could modify B this way:
Using a forward declaration basically tells the compiler that a type A will be defined somewhere else. The compiler can rely on this fact, but it does not know anything about A (particularly it ignores the size of A and its methods).
So inside B, if you have forward declared A, you can use only pointers to A classes (pointers have always the same size) and you can’t call any methods of an A class from inside B.