Reputation: 797
I have a header Room.h
defined as follows:
#ifndef ROOM_H
#define ROOM_H
class Room
{
public:
Room();
private:
Room north;
Room south;
Room east;
Room west;
};
#endif
But I get Error: incomplete type is not allowed
for each of the Room
variables. Is there a fundamental flaw in this kind of design?
Upvotes: 1
Views: 1173
Reputation: 7625
You are using Room
type before completely defining it (from definition the compiler deduce the size
which is required to create an object), and since it is same type inclusion, will lead to infinite definition. You can add pointer or reference to Room
instead of object.
class Room
{
public:
Room();
private:
Room* north;
Room* south;
Room* east;
Room* west;
};
Upvotes: 1
Reputation: 191
Use pointer.
private:
Room* north;
...
C++ compiler need know size of Class. Error: incomplete type is not allowed
, because cannot compute size.
Use pointer. Because compiler can compute size of pointer
.
PS : I'm not good at english
Upvotes: 6
Reputation: 490128
Yes, the design is fatally flawed. You're saying each room contains four other rooms. Each of those would then contain four more rooms--and each of those four more rooms, and so on indefinitely. In short, what started as a single room contains infinite other rooms.
You can create a room that contains pointers to four other rooms. Then you can create rooms for those to connect to, but (importantly) when you get to the end of a chain, you can create a room that has null pointers in directions where there are no more rooms.
Upvotes: 7