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.

  • 5
    If this code would work, these structs would be infinite in size. Which may require a significant RAM upgrade. – Eljay Jun 29 '21 at 16:22
  • Hmm, could you explain why? – guacamoleku Jun 29 '21 at 16:23
  • 3
    Because `Dweller` contains a `Room`, and a `Room` contains an unlimited amount of `Dweller`s? 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. – Sam Varshavchik Jun 29 '21 at 16:25
  • @guacamolest Because you have a circular reference. The room has dwellers and the dwellers themselves have a room associated. You need only one of these. – F. Müller Jun 29 '21 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++. – Sam Varshavchik Jun 29 '21 at 16:26
  • I think what you want to do is to change the two classes to contain *pointers* to each other. – Mark Lavin Jun 29 '21 at 16:27
  • Can i not make something similar to forward declaring in structs? Also, yeah that's a mistake on my part that the dwellers class doesn't have an initial size. – guacamoleku Jun 29 '21 at 16:27
  • 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. – Sam Varshavchik Jun 29 '21 at 16:28
  • I know that arrays have fixed size, I wanted to say that... Anyways, I think I understand – guacamoleku Jun 29 '21 at 16:31

1 Answers1

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;
    
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Mark Lavin
  • 1,002
  • 1
  • 15
  • 30