Previously asked operator= overload error and the question was closed due to being duplicate, tried to fix the code, and a new error emerged..
The old error is gone after const qualifying,
but a new error (which is a good thing?) occurs when trying to setName of ItemType due to “EXC_BAD_ACCESS (code=2, address=[address])”
[Minimal Reproducible Code]
main.cpp
#include "DoublySortedLinkedList.h"
int main() {
DoublySortedLinkedList<ItemType> m_List;
}
ItemType.h
#include <string>
using namespace std;
class ItemType {
public:
ItemType(int Id) {
m_Id = Id;
m_sName = "";
}
int GetId() const {
return m_Id;
}
string GetName() const
{
return m_sName;
}
void SetName(const string &inName) {
m_sName = inName;
}
void SetId(int inId) {
m_Id = inId;
}
ItemType& operator=(ItemType const &data) {
this->SetName(data.GetName());
this->SetId(data.GetId());
return *this;
}
protected:
int m_Id;
string m_sName;
};
DoublyIterator.h
#include "DoublySortedLinkedList.h"
template<typename T>
struct DoublyNodeType;
template<typename T>
class DoublySortedLinkedList;
template <typename T>
class DoublyIterator
{
friend class DoublySortedLinkedList<T>;
public:
DoublyIterator(const DoublySortedLinkedList<T>& list) : m_List(list), m_pCurPointer(list.m_pFirst) {};
T Next();
private:
const DoublySortedLinkedList<T>& m_List;
DoublyNodeType<T>* m_pCurPointer;
};
template <typename T>
T DoublyIterator<T>::Next() {
m_pCurPointer = m_pCurPointer->next;
return m_pCurPointer->data;
}
DoublySortedLinkedList.h
#include "ItemType.h"
#include "DoublyIterator.h"
# define min ItemType(INT_MIN)
#define max ItemType(INT_MAX)
template<typename T>
class DoublyIterator;
template <typename T>
struct DoublyNodeType
{
T data;
DoublyNodeType* prev;
DoublyNodeType* next;
};
template <typename T>
class DoublySortedLinkedList
{
friend class DoublyIterator<T>;
public:
DoublySortedLinkedList();
private:
DoublyNodeType<T>* m_pFirst;
DoublyNodeType<T>* m_pLast;
int m_nLength;
};
template <typename T>
DoublySortedLinkedList<T>::DoublySortedLinkedList() {
m_pFirst->data = min; // header // this is where the new error occurs when debugging
m_pLast->data = max; // trailer // probably this will cause the error
m_nLength = 0;
}