Im working on adding some operators to my linked list class. I did the += operator and works fine. However im attempting to make a copy construtor but im not getting any output. I dont have any errors but when after i do the copy in main for example
List linkedlist1;// i stored like 10 numbers in this list
List x(linkedlist1);
when i call
linkedlist1.print(); // works just fine
Your copy constructor doesn't quite copy everything. It's not copying the first node, it's just pointing to it. This will be a problem, as you'll end up deleting the same node multiple times.
You also don't initialize your variables (m_count is never initialized)
Try this:
1 2 3 4 5 6 7 8 9 10 11 12 13
List::List(const List& aList)
{
m_first = NULL; // initialize these
m_count = 0;
// m_first = aList.m_first; // get rid of this
ListNode* pTmp = m_first;
for(int i = 0; i < aList.get_count(); i++)
{
Add_To_Back(pTmp->m_element);
pTmp = pTmp->m_next;
}
}
I just made the changes you said and I get the following error
Unhandled exception at 0x00231ef9 in LinkedList.exe: 0xC0000005: Access violation reading location 0x00000000.
Are my steps right.
1. set m_first = NULL and count to 0 // basically an empty list for now
2. next I would think you have to make a ListNode* pTmp in order to traverse down aLIst, so go ahead and set that to aList.m_first instead of just m_first like above.
3. since i know how many nodes are on aList i would for loop; as long as i <aList.get_count()
4. for every iteration call the add_to_back(pTmp->m_element) which would get the element out of the current node pTmp, then simply update pTmp to the next node and do the same.
#ifndef LIST_H
#define LIST_H
#include <iostream>
#include "ListNode.h"
class List
{
public:
List();
List(const List& aList);
~List();
int get_count()const;//returns m_count which is modified when list is made
int count()const; //goes down list and counts
bool Delete_From_Front(int& element);
bool Delete_From_Back(int& element);
void Add_To_Front(constint& e);
void Add_To_Back(constint& e);
void List_To_Array(int*& pTr, int& size); //copy elements of a list to a dynamic array
void print()const;
int Max()const;
int Min()const;
int Total()const;
float Avg()const;
List& operator += (constint& element); // adds a number to end of list
//copy constructor
//array to list
// = operator
// + operator list + list and list + element
//sort
//insert sort??
private:
ListNode* m_first;
int m_count;
};
#endif