0

I have two classes: User.h and Room.h and both of them contain a pointer to an object of the other class (user to room and room to user). I think i understand how to include the .h files but i still get errors in one of my .cpp files (user.cpp).

user.h

#ifndef USER_H
#define USER_H

class Room;

using namespace std;

class User
{
private:
    Room* _currRoom;
public:
    //some functions...
};

#endif

room.h

#ifndef ROOM_H
#define ROOM_H

#include "User.h"

class Room
{
private:
    vector<User*> _users;
    User* _admin;
    int _maxUsers;
    int _questionTime;
    int _questionsNo;
    string _name;
    int _id;

public:
    Room(int id, User* admin, string name, int maxUsers, int questionsNo,int questionTime);
    //more functions...
};

#endif

I included user.h in room.cpp and room.h in user.cpp What is the problem with what I did?

abcdef123
  • 11
  • 1
  • 4

1 Answers1

0

In room.h, replace #include "User.h" with a forward declaration instead. Use forward declarations in the .h files, and move the corresponding #include statements to the .cpp files:

user.h

#ifndef USER_H
#define USER_H

class Room;

using namespace std;

class User
{
private:
    Room* _currRoom;
public:
    //some functions...
};

#endif

user.cpp

#include "user.h"
#include "room.h"
...

room.h

#ifndef ROOM_H
#define ROOM_H

#include <vector>
#include <string>

class User;

class Room
{
private:
    vector<User*> _users;
    User* _admin;
    int _maxUsers;
    int _questionTime;
    int _questionsNo;
    string _name;
    int _id;

public:
    Room(int id, User* admin, string name, int maxUsers, int questionsNo, int questionTime);
    //more functions...
};

#endif

room.cpp

#include "room.h"
#include "user.h"
...

If you don't do the forward declarations in this manner, you can end up in a circular situation where a header indirectly includes itself via another header (A includes B, which includes A) and thus its header guard has already been defined preventing its declarations from being processed, thus causing errors.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770