Reputation: 692
I have the class Agency
which has a private nested class Node
that should be used to build a linked list of Client
objects.
In order to add a node I need to use an overloaded +=
operator that receives a Client
object.
When I want to add the first object: the function calls the setHead
member of the Node
class.
But once I try to modify the data members of head
: data
to point to the received Client
object and next
to NULL
a run-time error occurs.
I can't figure out whats wrong, the Client
object is passed as it should be (I checked it) - I think that I'm missing something in the declaration of setHead
's arguments.
would be thankful for any advice.
btw, I have to use the existing private members as they are and setHead
method must receive a pointer to Client
.
Agency.h
class Agency
{
public:
Agency(); //ctor
Agency& operator+=(const Client&); //overloaded += operator
~Agency(); //dtor
private:
class Node //node as nested class
{
public:
Node(); //ctor
void setHead(Client*&); //set head node
private:
Client* data; //points to Client
Node* next; //points to next node on the list
};
Node *head; //points to head node of database
};
Agency.cpp relevant methods
void Agency::Node::setHead(Client*& temp)
{
data = temp;
next = NULL;
}
Agency& Agency::operator+=(const Client& client_add)
{
Client* temp = new Client (client_add); //new client object is created using clients copy ctor
if (!head) //if the head node is NULL
{
head->setHead(temp); //assign head node to point to the new client object
}
return *this;
}
EDIT: Thanks for the reply, I have yet another question:
I want to have a method of Node
that will return a pointer to Node
, here is the declaration:
`Node* nextNode(Node*);`
Function:
`Node* MatchmakingAgency::Node::nextNode(Node* start)`
Causes compilation error: 'Node' does not name a type
How can I properly declare such a method?
Upvotes: 0
Views: 2595
Reputation: 238421
In this code:
if (!head) //in the head node is empty
{
head->setHead(temp);
head
is not "empty". It's a null pointer. And then you dereference the null pointer which results in undefined behaviour.
Perhaps you meant to have this:
head = new Node();
before setHead
.
Upvotes: 3