0

I'm fairly new to c++ so i'm having a bit of trouble wrapping my head around forward declarations.

I have two header files which #include eachother as they both have structs that reference eachother. I've seen from many other answers that I need to forward declare these structs, so that I can do this. Here is how i implemented that:

Parser.h

namespace Variables
{
struct Variable;
}
#include "variables.h"

namespace Parser
{
struct Node
{
  int type;
  Variables::Variable variable;
  int skip;
  Parser::Function fn;
  Parser::Node *parent;
};
}

Variables.h

namespace Parser
{
struct Node;
}

#include "parser.h"

namespace Variables
{
typedef struct Variable
{
  int type;
  std::string name;
  Variables::Expression int_value;
  int scope;
  Parser::Node *parent;
} Variable;
}

This seemed to work, however it complained about the Node struct having a member of incomplete type(the Variables::Variable) which I found out was because you have to do a const value when it's forward declared, so I made it a pointer:

struct Node
{
  int type;
  Variables::Variable *variable;
  int skip;
  Parser::Function fn;
  Parser::Node *parent;
};

Is there a way that I can implement this where I don't have to make Variables::Variable a pointer?

dwib
  • 583
  • 4
  • 19
  • You have to use a pointer if you have an incomplete type, which you have to have. related/dupe: https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes – NathanOliver Apr 01 '20 at 15:21
  • This doesn't address the question, but it's unusual to have definitions and declarations followed by a `#include` directive. Usually the `#include` directives come first. – Pete Becker Apr 01 '20 at 15:28
  • My code doesn't compile when i do the forward declaration after the `#include` – dwib Apr 01 '20 at 15:33
  • Does this answer your question? [Resolve build errors due to circular dependency amongst classes](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes) – Mikel Rychliski Apr 10 '20 at 01:31

0 Answers0