From the thread in
When should I use the new keyword in C++?
The answer talks about when "new" must be used in order to create a pointer to an object if you need to return the pointer to the object from the function.
However, my code below works fine. I use a local pointer instead of allocating some memory to a new pointer.
node* queue::dequeue(){
if(head==0){
cout<<"error: the queue is empty, can't dequeue.\n";
return 0;
}
else if(head->next !=0){
node *tmp=head;
head=head->next;
tmp->next=0;
return tmp;
}
else if(head->next ==0){
node *tmp=head;
head=0;
tmp->next=0;
return tmp;
}
}
It is a simple dequeue() operation. My tmp is a local pointer. But i still return it.
Credit to Mahesh
I have following statements in the main()
node a8(8); //node constructor with the value
Therefore tmp points to what head points to, and head points to different nodes like a8.
Since a8 is valid throughout the main(), tmp is valid throughout the main() as well