Reputation: 11
I am creating and displaying an singly linked list. However there is an error in the main function
no matching function for call to ‘node::node()’
Following is my code:
#include <iostream.h>
using namespace std;
class node
{
node *next,*start,*ptr;
int data;
public:
node(int d)
{
data=d;
next=NULL;
start=NULL;
ptr=NULL;
}
void create();
void display();
};
void node::create()
{
int d;
char ch;
node *temp;
do
{
cout<<"Enter data";
cin>>d;
temp=new node(d);
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
temp->next=NULL;
}
cout<<"\nDo you want to enter more data?";
cin>>ch;
}while(ch=='y'||ch=='Y');
}
void node::display()
{
ptr=start;
while(ptr->next!=NULL)
{
cout<<"\n"<<ptr->data;
ptr=ptr->next;
}
cout<<"\n"<<ptr->data;
}
int main()
{
node n;
int c;
char a;
do
{
cout<<"*****MENU*****";
cout<<"\n1.Create \n2.Display";
cout<<"\nEnter your choice";
cin>>c;
switch(c)
{
case 1:
n.create();
break;
case 2:
n.display();
break;
default:
cout<<"\nInvalid choice";
break;
}
cout<<"\nDo you want to continue?";
cin>>a;
}while(a=='y'||a=='Y');
return 0;
}
When I write the same program using a friend class of node, the program executes successfully. Why do we need to use more than one class?
Upvotes: 0
Views: 8974
Reputation: 44258
For your class node
you defined only one constructor, that accepts parameter type int
, which means you can construct instances of this class with such parameter, what you do here:
temp=new node(d); // fine, you pass int d to construct node
but in main()
you try to create instance of class node
without any parameters:
int main()
{
node n; // <---- problem
so either pass integer when you create n
in main()
or define another constructor without any parameters (aka default constructor) for class node
.
Upvotes: 2