1

I am trying to define two structs inside a header file that both of them contain each other as objects. More specifically:

typedef struct Dweller {
    int id;
    int age;
    std::string name, lastname;

    Room room;

    float foodconsume;
    float waterconsume;
};

typedef struct Room {
    int id;

    int WIDTH = 400;
    int HEIGHT = 100;

    std::vector<Dweller> dwellers;
    float energyconsumed;
    int property;
    int floor, roomno;
};

But as you might have noticed, this is an issue because the Dweller doesn't know what Room is at that point of the code. I am using C++, and I am aware that I can make them classes, then forward declare them. But I want to know if I can achieve something like this without getting them into classes. I also want to use them seperately, so I don't want one of them getting declared inside other one.

9
  • 5
    If this code would work, these structs would be infinite in size. Which may require a significant RAM upgrade. Commented Jun 29, 2021 at 16:22
  • Hmm, could you explain why? Commented Jun 29, 2021 at 16:23
  • 3
    Because Dweller contains a Room, and a Room contains an unlimited amount of Dwellers? There's also a little problem that Dweller dwellers[]; is not valid C++. But, whatever the size of this array is, you have both classes containing each other. That's the reason for the serious RAM upgrade. Commented Jun 29, 2021 at 16:25
  • 5
    P.S.: whichever C++ textbook youi're using that gives an example of "typedef struct"-something: you should replace it with a better C++ textbook. You only need to do something like that in C, but not C++. Commented Jun 29, 2021 at 16:26
  • 5
    A forward declaration won't help you when class A contains B, and class B contains A. This will require an infinite amount of RAM. And there is no such thing as an "initial size" of arrays in C++. In C++ all arrays have a fixed size. Commented Jun 29, 2021 at 16:28

1 Answer 1

3

Several things:

  1. As Sam said, get rid of the typedefs.

  2. Change the declaration Room room in Dweller to Room* room and vice versa.

  3. To satisfy the compiler, put two forward declarations up front:

    struct Dweller;
    struct Room;
    
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.