Structures Problem

I have a code :
struct Node
{
struct Node (int data)
{
this->data = data;
}
int data;
};

int main ()
{
return 0;
}

I read that we can initialize the structure inside the stucture. But my compiler gives an error when I do that. The error occurs on the definition of structure twice
this->data =data is weird

1
2
3
4
struct Node (int newData)
{
    data = newData;
}


is better. the error you are getting is because "struct" in struct Node (int data) remove the word struct. Post the entire code using the "<>" (code) tag from the format menu
Last edited on
I think the best way to do it would be

1
2
3
4
5
6
7
struct Node {
    int data;

    Node(int newData) : data(newData) {
    } 

}


I think this is actually more efficient than initializing the variable in the body. But this should work too
1
2
3
4
5
6
7
8
struct Node {
    int data;

    Node(int data){
        this->data = data;
    } 

}


And there's nothing weird about using the this keyword, it's perfectly fine.

If that doesn't solve your problem, tell us what the error is.
Last edited on
Topic archived. No new replies allowed.