Home > OS >  why cannot we initialize a node without using a pointer?
why cannot we initialize a node without using a pointer?

Time:02-17

I have recently started learning data structure and as a beginner, I have a query while implementing linked list nodes, why do we have to initialize node using a pointer only?

class node{
    public:
    int data;
    node* next;
    node(int val){
        data = val;
        next = NULL;
    }
 };
 int main(){
    node* head = NULL;
    node head = NULL; // this throws an error which i cannot understand
 }

CodePudding user response:

Actually you can initialize the node by value. If you want to initialize a node with value, according to your constructor node(int val), you have to code like below:

class node{
    public:
    int data;
    node* next;
    explicit node(int val){
        data = val;
        next = NULL;
    }
 };
 int main(){
    int value = 777;
    //node* head = NULL; // Initialize head pointers to null
    node head(value);   // By your constructor definition
 }

EDIT: By the way, marking a constructor as explicit is a very good habit to have, as it prevents unexpected conversion, as Duthomhas commented.

  • Related