I’m trying to create a linked list for a project. I’ve got these two file (one .h and one .cpp). I’m not sure how to make a copy constructor so I’m not sure if that has anything to do with it. I suppose if someone wanted to point me in the right direction on that as well, it would be helpful. Thank you.
#include <iostream>
#include "studentList.h"
using namespace std;
// Default Constructor for StudentList
// Creates Dummy Head Node for a new empty list
StudentList::StudentList ()
{
// Create the dummy head node
Node* Head; // Creates Head Node
Head = new Node;
Head->next = NULL; // Sets pointer to NULL by default
}
//Copy Constructor
StudentList::StudentList(const StudentList& list)
{
}
void StudentList::addStudentList(Student newStudent)
{
Getting the error here!!!!!!
if (Head->next == NULL)
{
Head->next->student = newStudent;
Head->next->prev = Head;
Head->next->next = NULL;
}
}
Here is the .h file
#include <iostream>
#include "Student.h"
using namespace std;
class StudentList{
public:
//Default Constructor
StudentList();
//Copy Constructor
StudentList(const StudentList& list);
//Add Student Method
void addStudentList(Student);
private:
// Node struct to hold Student data and with pointers to a previous and next node in linked list
struct Node {
Student student;
Node* prev;
Node* next;
};
};
Headis supposed to be a member. The pointerHeadyou create has automatic storage. It goes out of scope when the constructor is finished, and you get a dangling reference.On a side note, you should indent the code you put between curly braces. It makes it easier fo the human reader to group related elements together, an to spot code blocks.
As for the copy c’tor, as you can see, it takes a reference to an existing object, and constructs a new one out of it. The defaulut copy c’tor supplied by the compiler does a shallow copy. Meaning is
aandbare lists, thana.Headandb.Headpoint to the same starting elements. You can overrride it to do a deep copy with something like this:I of course neglected
tmp->prevbut that’s the general idea for a signly linked list.