Search code examples
c++listthis

linked list c++ difference between void function and return this


I have a question about the differences between 2 styles of coding:

void *addfirst (int data){
     head = new Node(int data, head);
     return;
}

and the second is:

LinkedList *addfirst (int data){
     head = new Node(int data, head);
     return this;
}

My prof said that nowadays most people prefer the second choice, but I don't know if there was any advantages, compare with the first one?


Solution

  • void *addfirst (int data){
         head = new Node(int data, head);
         return;
    }
    

    The function is declared to return an object of type void*. The function returns by returning nothing. The behaviour of the program is undefined.

    LinkedList *addfirst (int data){
         head = new Node(int data, head);
         return this;
    }
    

    This function does return an object. The behaviour is well defined.