-1

I have a class "Nodes" and a struct "Mark". Objects from "Nodes" have an element of struct "Mark", and objects of "Mark" have an element of class "Nodes".

struct Mark {
    int q;
    Nodes start;
};

class Nodes {
protected:
    string Node_Name;       
    Mark mark;  
};

The problem are errors: C2027 (use of undefined type 'type') or C2029 (class Nodes). So I can't change the positions of defining these things, because I would get new error (e.g. C2027 if it was C2029 before). How could I tackle this problem?

  • 3
    If they really contained each other, then they would have infinite size. Maybe you meant pointers instead? In that case, you could simply use forward declaration. – Karsten Koop Jul 23 '18 at 13:39
  • 1
    Please copy-paste the error messages into the question. Some of us don't memorize the error codes. – Algirdas Preidžius Jul 23 '18 at 13:39

1 Answers1

2

This does not work. If every Node contains a Mark and every Mark contains a Node, you will have an unending chain of instances.

You probably meant that they have references to each other?

If so, you should use a pointer or preferably a smart pointer.

Even then, the compiler has to know the types exist before parsing, so you need a forward declaration:

class Nodes;

struct Mark {
    int q;
    Nodes* start;
};

class Nodes {
protected:
    string Node_Name;       
    Mark* mark;  
};

Alternatively, using smart pointers (you will need to check which smart pointer you need, I took an educated guess and assumed you need a shared pointer):

#include <memory>

class Nodes;

struct Mark {
    int q;
    std::shared_ptr<Nodes> start;
};

class Nodes {
protected:
    string Node_Name;       
    std::shared_ptr<Mark> mark;  
};
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • I recommend appending your answer with an example using a smart pointer. – Thomas Matthews Jul 23 '18 at 13:53
  • Thanks! But now I have a new error: C2678 (binary 'operator' : no operator defined which takes a left-hand operand of type 'type' (or there is no acceptable conversion)). – Anton Ryabtsev Jul 23 '18 at 13:54
  • I cannot see how that would happen with the code you showed us. Could you please post a [mcve]? – nvoigt Jul 23 '18 at 13:55
  • In my situation I need Mark refering to Nodes only. So how could I make a ref (I mean something like that: `Mark mark; Nodes node; mark.start = node;`) – Anton Ryabtsev Jul 23 '18 at 14:15
  • That seems like an easy question, but in C or C++ it's really not. I'm afraid a simple sample would not help you much and only steer you into the next avalanche of errors (compile time and runtime). I would suggest reading a good book (I'm a fan of dead wood personally) or online tutorial on the topic of "pointers" and "references" in C++. As a hint: if it's less than 10 pages, it does not even start to cover the topic. – nvoigt Jul 23 '18 at 14:31