2

While solving questions related to linked lists in C++, the struct definition for implementation of list was given as follows.

Struct node{
  int data;
  node *next;
  node(int x) : data(x), next(NULL) {}
};

what is the significance of 3rd line : " node(int x) : data(x), next(NULL) {} ".

Accessing it as a function is giving runtime error. Please share some resources where I can get a better understanding of the topic.

P.S.- I have just shifted from C to C++.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60

1 Answers1

3

node(int x) : data(x), next(NULL) {}

If you are from python background, then it is same as

class Node: 
    
    def __init__(self, x): 
        self.data = x
        self.next = None

struct is same as class except everything is public by default in cpp strict. struct is an object in cpp, so it needs a constructor.

Please share some resources where I can get a better understanding of the topic.