Search code examples
c++pointersc-preprocessorclass-design

C++ classes with members referencing each other


I'm trying to write 2 classes with members that reference each other. I'm not sure if I'm doing something wrong or it's just not possible. Can anyone help me out here...

Source.cpp

#include "Headers.h"
using namespace std;

void main()
{
    Network* network = new Network();

    system("pause");
    return;
}

Headers.h

#ifndef Headers_h
#define Headers_h

#include <iostream>
#include <vector>
#include "Network.h"
#include "Router.h"

#endif

Network.h

#include "Headers.h"

class Network
{
protected:
    vector<Router> Routers;
};

Router.h

#include "Headers.h"

class Router
{
protected:
    Network* network;
public:
};

The errors I'm getting are:

error C2143: syntax error : missing ';' before '<'
error C2238: unexpected token(s) preceding ';'
error C4430: missing type specifier - int assumed.

I'm pretty sure I'm not missing any semicolons or stuff like that. The program works find if I take out one of the members. I tried finding similar questions and the solution was to use pointers, but that's what I'm doing and it does't seem to be working!


Solution

  • first error - you need to explicitly use the namespace:

    std::vector<Router> Routers;
    

    Don't "use namespace std;" in header files

    Other errors are restulting from the first :)

    As to the referencing to the class defined later, you need to do forward declaration of Router class, put

    class Router;
    

    into your Network.h