This code doesn’t do anything special. It’s just a snippet to show the problem with forward declarations. Just a short question: why doesn’t it work and how to force it to work?
class A;
class B {
A obj;
public:
int getB() const {
return 0;
}
void doSmth() {
int a = obj.getA();
}
};
class A {
B obj;
public:
int getA() const {
return 1;
}
void doSomething() {
int b = obj.getB();
}
};
This code gives me errors:
error C2079: 'B::obj' uses undefined class 'A'
error C2228: left of '.getA' must have class/struct/union
That type of circular dependency is not possible in C++. You can’t have objects containing each other. You can however store pointers or references. You also can’t really use a method of a class without the full definition.
So, there’s two things you need to do:
1) Replace the objects with pointers.
2) Implement the method after the class definitions. If these are in a header, you’ll need to mark them as
inlineto prevent multiple definitions.