Mustafa
Mustafa

Reputation: 590

declaring a struct in another struct

in my header file:

private:
struct movieNode {
    string title;

    castNode *castHead;

    movieNode *prev;
    movieNode *next;
};

struct castNode {
    string name;

    castNode *next;

};

movieNode *head;
movieNode *last;

but the compiler error is:

expected ';' before '*' token

my aim is that every movieNode should have a title and a cast list (with castNode). thanks in advance.

Upvotes: 1

Views: 135

Answers (3)

Quentin Perez
Quentin Perez

Reputation: 2903

private:
     struct castNode; // <- add this
     struct movieNode
     {
             string     title;
             castNode*  castHead;
             movieNode* prev;
             movieNode* next;
     };
     struct castNode
     {
             string    name;
             castNode* next;
     };
     movieNode*   head;
     movieNode*   last;

Upvotes: 4

naren.katneni
naren.katneni

Reputation: 285

Declare castNode before movienode.

Only then movienode "knows" what a castNode is.

Upvotes: 2

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

movieNode needs to at least be able to see an incomplete type called castNode. At the moment, the compiler is going "Huh, castNode? What the hell is that?" because it hasn't seen the definition of castNode yet. You can avoid it in this case by simply defining castNode before you define movieNode. Just swap the two structs around.

In other cases, where you have a cyclic dependency (if castNode had a pointer to a movieNode too, for example), you can use a forward declaration to provide an incomplete type (it would look like class castNode;) and then define it properly later.

Upvotes: 6

Related Questions