I have two classes declared as below:
class User
{
public:
MyMessageBox dataMsgBox;
};
class MyMessageBox
{
public:
void sendMessage(Message *msg, User *recvr);
Message receiveMessage();
vector<Message> *dataMessageList;
};
When I try to compile it using gcc, it gives the following error:
MyMessageBox does not name a type
It is always encouraged in C++ that you have one class per header file, see this discussion in SO [1].
GManNickG answer's tells why this happen. But the best way to solve this is to put User
class in one header file (User.h
) and MyMessageBox
class in another header file (MyMessageBox.h
). Then in your User.h
you include MyMessageBox.h
and in MyMessageBox.h
you include User.h
. Do not forget "include gaurds" [2] so that your code compiles successfully.
On a related note, if you had:
class User; // let the compiler know such a class will be defined
class MyMessageBox
{
public:
User* myUser;
};
class User
{
public:
// also ok, since it's now defined
MyMessageBox dataMsgBox;
};
Then that would also work, because the User is defined in MyMessageBox as a pointer
C++ compilers process their input once. Each class you use must have been defined first. You use MyMessageBox
before you define it. In this case, you can simply swap the two class definitions.
You need to define MyMessageBox before User -- because User include object of MyMessageBox by value (and so compiler should know its size).
Also you'll need to forward declare User befor MyMessageBox -- because MyMessageBox include member of User* type.
You must declare the prototype it before using it:
class User;
class MyMessageBox
{
public:
void sendMessage(Message *msg, User *recvr);
Message receiveMessage();
vector<Message> *dataMessageList;
};
class User
{
public:
MyMessageBox dataMsgBox;
};
edit: Swapped the types
Source: Stackoverflow.com