0

I implemented a linked list in C++. I implemented it properly, however when I made a small change to my code, it gave me an error.
I changed
LinkedList l;
to
LinkedList l=new LinkedList();

It gave me the following error:

"conversion from ‘LinkedList*’ to non-scalar type ‘LinkedList’ requested"

Can anyone please tell me why?

Here is my code:

#include<iostream> using namespace std; class Node { public: int data; Node *next; Node(int d) { data=d; next=NULL; } }; class LinkedList { public: Node *head; LinkedList() { head=NULL; } void add(int data) { Node *temp,*t=head; if(head==NULL) { temp=new Node(data); temp->next=NULL; head=temp; } else { temp=new Node(data); while(t->next!=NULL) t=t->next; t->next=temp; temp->next=NULL; } } void Display() { Node *temp=head; cout<<temp->data<<"\t"; temp=temp->next; while(temp!=NULL) { cout<<temp->data<<"\t"; temp=temp->next; } } }; int main() { LinkedList l=new LinkedList(); l.add(30); l.add(4); l.add(43); l.add(22); l.Display(); } 

2 Answers 2

3

You want this instead:

LinkedList * l = new LinkedList(); 

Note that the new operator returns a pointer (Foo *) to an object allocated on the heap.

Alternatively, more efficiently, and simpler for your purposes, you could just allocate the LinkedList as a local stack variable:

LinkedList l; 

Then, you wouldn't have to worry about freeing the pointer (using delete), and the following dot operator use could remain.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

LinkedList *l=new LinkedList();

l->add(30);

When you use 'new' the return value is a pointer, not the object itself, so you have to declare the type as a pointer.

Don't forget to delete l at the bottom. You could also just say:

LinkedList l;

l.add(30);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.