0
#include <stdio.h>

struct B;
struct A {
    B* b;
    int num = 4;
    
    A() {
        b = new B(this);
    }
};

struct A;
struct B {
    A* a;
    int num = 21;
    
    B(A* a) {
        this->a = a;
    }
    
    // function that does stuff with both A and B nums
    int add() {
        return num + a->num;
    }
};

int main()
{
    A thing;
    printf("%d",thing.b->add());
    return 0;
}

So I have two structs in my code, where struct B is a member of struct A. I just want them to store pointers to each other so that they can access each other's member variables. Is this even possible? I'm open to refactor suggestions.

ankien
  • 25
  • 1
  • 7
  • Yes that's possible. To dereference the pointer, the full class definition needs to be visible at that point though. – πάντα ῥεῖ Dec 14 '20 at 07:57
  • The first question is going to be "Why?" as this is an unusual thing to do and complicates memory management significantly. – tadman Dec 14 '20 at 07:57
  • Presumably your code is giving an error? Are `A` and `B` declared in different files? Moving the definitions of your functions out of line is probably the way to fix it – Alan Birtles Dec 14 '20 at 07:59

1 Answers1

0

It's possible but you're going to have to move some code around because many expressions cannot be compiled until the type is fully known. For instance new B(this) cannot be compiled until B is fully known.

So the A constructor needs to be compiled after B is defined, like this

struct B;

struct A {
    B* b;
    int num = 4;
    
    A();
};

struct B {
    A* a;
    int num = 21;
    
    B(A* a) {
        this->a = a;
    }
    
    // function that does stuff with both A and B nums
    int add() {
        return num + a->num;
    }
};

inline A::A() {
    b = new B(this);
}

int main()
{
    A thing;
    printf("%d",thing.b->add());
    return 0;
}
john
  • 85,011
  • 4
  • 57
  • 81
  • Thank you, that works! I didn't know `inline` could be used to control what the compiler sees. – ankien Dec 14 '20 at 08:13
  • @ankien It's the order of the definitions that is controlling what the compiler sees. The code would compile perfectly well without `inline`. I just put it there because `A::A()` was inline in your original code because it was inside the class. Now it's outside the class you have to add `inline` if that is what you want it to be. – john Dec 14 '20 at 08:22
  • @ankien it doesn't control what the compiler sees, its just a hint to the linker that it is OK to have multiple copies of a function, its required when defining functions outside of a class in a header file – Alan Birtles Dec 14 '20 at 08:22