#include <stdio.h>
struct classOne; struct classTwo; struct classOne {
public:
classTwo* two;
int a = 32;
};
struct classTwo {
public:
classOne* one;
int b = 64;
};
int main() {
classOne cls;
cls.two = new classTwo; printf("%d", cls.two->b);
return 0;
}
A class (or struct) declaration does not create an object. It creates a
template for objects. You need to explicitly create both objects and somehow set the pointers. In the code above I allocated the
classTwo
object with new. Alternatively you can allocate it statically:
int main() {
classOne cls;
classTwo cls2;
cls.two = &cls2; printf("%d", cls.two->b);
return 0;
}
In any case the pointer(s) needs to be initialized.
One more thing: the syntax you used
int a=32;
is not idiomatic. It is legal (since C++11) but it's not how typically objects are initialized.
The "classical" way is to have a constructor initialize all members. In you particular case a constructor for
classOne
could look like this:
struct classOne {
classOne (classTwo* the_two) : a(32), two(the_two) {};
classTwo* two;
int a;
};