mardi 21 juillet 2020

difference between node* ptr= new node(); vs node* ptr=new node;? [duplicate]

I am new to Object Oriented Programming and i am not able to find correct explanation for following:-

//type-1:


#include <bits/stdc++.h> 
using namespace std; 

class node { 
public: 
    int data; 
    node* next; 
}; 

// This function prints contents of linked list 
// starting from the given node 
void printList(node* n) 
{ 
    while (n != NULL) { 
        cout << n->data << " "; 
        n = n->next; 
    } 
} 


int main() 
{ 
    node* head = NULL; 
    node* second = NULL; 
    node* third = NULL; 

    // allocate 3 nodes in the heap 
    head = new node; 
    second = new node; 
    third = new node; 

    head->data = 1; // assign data in first node 
    head->next = second; // Link first node with second 

    second->data = 2; // assign data to second node 
    second->next = third; 

    third->data = 3; // assign data to third node 
    third->next = NULL; 

    printList(head); 

    return 0; 
} 

type-2:

#include <bits/stdc++.h> 
using namespace std; 

class node { 
public: 
    int data; 
    node* next; 
}; 

// This function prints contents of linked list 
// starting from the given node 
void printList(node* n) 
{ 
    while (n != NULL) { 
        cout << n->data << " "; 
        n = n->next; 
    } 
} 


int main() 
{ 
    node* head = NULL; 
    node* second = NULL; 
    node* third = NULL; 

    // allocate 3 nodes in the heap 
    head = new node(); 
    second = new node(); 
    third = new node(); 

    head->data = 1; // assign data in first node 
    head->next = second; // Link first node with second 

    second->data = 2; // assign data to second node 
    second->next = third; 

    third->data = 3; // assign data to third node 
    third->next = NULL; 

    printList(head); 

    return 0; 
} 

Both the code are working absolutely fine. please tell me the difference between (head= new node) vs (head=new node()) on line 6 in both the code inside main function , what value does parenthesis add here? What is suggested or which one is better to use?

Aucun commentaire:

Enregistrer un commentaire