I am trying to make a class that contains two other objects, and those object should maintain a pointer to the class they are contained in. For
For example… (I am only using on object instance variable, in the final imagine there is a class very similar to ClassB)
This is just my main.cpp, figured I would include it to be thorough…
//Filename: main.cpp
#include "ClassA.hpp"
int main(int argc, char **args) {
ClassA *a = new ClassA();
// There would be some more here in the real code
return 0;
}
Now for the classes in questions….
//Filename: classA.hpp
#ifndef CLASSA_H
#define CLASSA_H
#include "ClassB.hpp"
class ClassA {
public:
ClassA() {
b = new B(this);
};
virtual ~ClassA();
private:
ClassB *b;
};
#endif //CLASSA_H
Now here is the other file…
#ifndef CLASSB_H
#define CLASSB_H
#include "ClassB.hpp"
//Filename: classB.hpp
class ClassB {
public:
ClassB(ClassA *parent) {
this->parent = parent;
};
virtual ~ClassB();
private:
A *parent;
};
#endif //CLASSB_H
When I try to compile this, I am getting the error “error: ClassA does not name a type” and then of course “error: expected ‘)’ before ‘*’ token”
My guess is this has something to with them including one another?
(Not sure if it matters, but in the actual code, the function implementations are in a .cpp file that includes the header. Would that do it?)
Add
before ClassB definition;
Simple example: