lemonader lemonader - 17 days ago 7
C++ Question

Xcode C++ Struct Order

The code is given below is not allowed to compile because of struct's order. song_node struct has playlist variable and playlist struct has song_node variable.

This code is runned on Visual Studio or gcc compile.

struct song_node {
song* data;
song_node* next;
song_node* prev;
playlist* parent;
};

struct playlist {
int songnumber;
char* name = new char[LNAME_LENGTH];
song_node* head;
playlist* next;
playlist* prev;
};


I am new on Xcode. What is the problem in this code?

Answer

You need to do a forward declaration.

struct playlist;

struct song_node {
    song* data;
    song_node* next;
    song_node* prev;
    playlist* parent;
};

struct playlist {
    int songnumber;
    char* name = new char[LNAME_LENGTH];
    song_node* head;
    playlist* next;
    playlist* prev;
};

The compiler needs to know that there is something like a playlist when you want to use it within song_node. By forward-declaring playlist you tell the compiler that such an object exists.

Comments