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
When the compiler compiles the class
User
and gets to theMyMessageBox
line,MyMessageBox
has not yet been defined. The compiler has no ideaMyMessageBox
exists, so cannot understand the meaning of your class member.You need to make sure
MyMessageBox
is defined before you use it as a member. This is solved by reversing the definition order. However, you have a cyclic dependency: if you moveMyMessageBox
aboveUser
, then in the definition ofMyMessageBox
the nameUser
won’t be defined!What you can do is forward declare
User
; that is, declare it but don’t define it. During compilation, a type that is declared but not defined is called an incomplete type. Consider the simpler example:By forward declaring
User
,MyMessageBox
can still form a pointer or reference to it:You cannot do this the other way around: as mentioned, a class member needs to have a definition. (The reason is that the compiler needs to know how much memory
User
takes up, and to know that it needs to know the size of its members.) If you were to say:It wouldn’t work, since it doesn’t know the size yet.
On a side note, this function:
Probably shouldn’t take either of those by pointer. You can’t send a message without a message, nor can you send a message without a user to send it to. And both of those situations are expressible by passing null as an argument to either parameter (null is a perfectly valid pointer value!)
Rather, use a reference (possibly const):