1

I did something like this:

struct Vertex {
  list<Edge*> edges;
};

struct Edge {
  Vertex* v1;
  Vertex* v2;
};

and the compiler error :

'Edge' was not declared in this scope

How do I solve this problem without putting these two into separate headers, "vertex.h" and "edge.h"?

chris
  • 60,560
  • 13
  • 143
  • 205
JASON
  • 7,371
  • 9
  • 27
  • 40

3 Answers3

5

Use forward declaration before you use Edge.

struct Edge;

struct Vertex 
{
    list<Edge*> edges;
};

Note that when you forward declare a type the compiler treats the type as an Incomplete type, it does not know anything about the layout of the type but it just knows that the type exists, So there are some limitations of how you can use an Incomplete type.

Good Read:
When can I use a forward declaration?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

You can forward-declare the type:

struct Vertex;
struct Edge {
   Vertex* v1;
   Vertex* v2;
};

That being said, having a vertex know its list of edges is probably not a good design for a graph; what if you want to reuse the same vertex in multiple graphs? (As an example, an airport may be a reasonable vertex in multiple different itineraries used by different people).

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • can't you use shared_ptr vertex instead? I fail to see your point here. – Chubsdad Dec 11 '12 at 05:27
  • A valid use of such design would be a triangulation. Sometimes you want to enumerate the edjes adjacent to a vertex. Besides if we remove edges from the class as it stands then a vertex has no members at all. 8 - ) – Alexander Chertov Dec 11 '12 at 05:27
  • But sure, you can have a class that stores the coordinates, and another one on top of it that knows about adjacent edges. – Alexander Chertov Dec 11 '12 at 05:28
  • @Chubsdad, it isn't about memory management, but about clarity of the API. It would be very weird to have a vertex contain a list of edges, where the list of edges includes edges from two separate graphs. A better API would be to provide a method on the Graph object that enumerates edges that include the given vertex. – Michael Aaron Safyan Dec 11 '12 at 05:47
  • @AlexanderChertov, agreed that it is useful to map from a vertex to its adjacent edges, just suggesting that making it a function on the graph rather than on the vertex might be a better decision. – Michael Aaron Safyan Dec 11 '12 at 05:48
1

If your types use each other through pointers you can forward-declare one of them before defining the other one. For example like this:

struct Vertex;
struct Edge { Vertex* v1; Vertex* v2; };
struct Vertex { list<Edge*> edges; };
Alexander Chertov
  • 2,070
  • 13
  • 16