Reputation: 1603
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();
}
Upvotes: 0
Views: 308
Reputation: 6049
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);
Upvotes: 1
Reputation: 2906
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.
Upvotes: 3