I am doing programming project 6 of chapter 13 of Problem Solving With C++ Global Edition by Savitch. I am trying to overload the << operator to print the list. It works up to the point where my walker pointer is assigned to the value of the head pointer for the 2nd time, making it impossible for me to use the list as a circularly linked list which is the project requirement. I've recreated the most basic form of the source of the crash here:
Suitors.h file:
#include <iostream>
struct Suitor {
int number;
Suitor *link;
};
class Suitors {
private:
Suitor *head=nullptr;
int size=0;
public:
//Constructors
Suitors(int sizePar);
~Suitors(); //Destructor
//Print list
friend std::ostream& operator<<(std::ostream& outs, const Suitors& list);
};
Suitors.cpp File:
#include "Suitors.h"
Suitors::Suitors(int sizePar) {
Suitor *tempPtr = new Suitor;
size = sizePar;
for (int i=0; i<size; i++) {
if (head==nullptr) {
head = tempPtr;
}
tempPtr->number = i+1;
if (i==size-1) {
tempPtr->link = head;
}
else {
tempPtr->link = new Suitor;
}
tempPtr = tempPtr->link;
}
}
Suitors::~Suitors() {
Suitor *walker1 = head, *walker2 = head;
for (int i=0; i<size; i++) {
walker1 = walker1->link;
delete walker2;
walker2 = walker1;
}
head = nullptr;
}
std::ostream& operator<<(std::ostream& outs, const Suitors& list) {
Suitor *walker = list.head;
walker = walker->link;
walker = list.head;
/*
for (int i=0; i<list.size; i++) {
outs << walker->number << " ";
walker = walker->link;
}
*/
}
main.cpp file:
#include <iostream>
#include "Suitors.h"
void project6();
int main() {
std::cout << "Hello, World!" << std::endl;
project6();
return 0;
}
void project6() {
Suitors six(6);
std::cout << six << std::endl;
}
I've trimmed down the << operator overloading to just what creates the error. walker is set to the list head, then advanced a node, then set back to the list head, causing the error. The desired behavior is to be able to set walker to the head node more than once.