Hi every one. I want to understand how pointers works and how to do a deep copy of a class.
Here is my class and the problems with it
.h
class Linked
{
public:
Linked();
virtual ~Linked()
Linked(const Linked& cap);
const Linked& operator=(Linked& cap);
Linked *prev;
Linked *next;
CString Name;
CPoint Position;
}
.cpp
Linked::Linked(){
next = NULL;
prev = NULL;
}
Linked::~Linked(){
delete next;
next = NULL;
delete prev;
prev = NULL;
}
Linked::Linked(const Linked& cap){
Name = cap.Name;
Position = cap.Position;
next = new Linked();
next = cap.next;
prev = new Linked();
prev = cap.prev;
}
const Linked& Linked::operator=(const Linked& cap){
if(this == cap)
return *this;
delete prev;
delete next;
Name = cap.Name;
Position = cap.Position;
if(cap.next){
next = new Linked();
next = cap.next;
}else{
next = NULL;
}
if(cap.next){
next = new Linked();
next = cap.next;
}else{
next = NULL;
}
}
Now in other .cpp file I populated the Linked list
....
CArray <Linked, Linked&> Lists;
for(int i = 0; i < 10; i++){
Linked item;
item.Name.Format("Node_%d",i);
item.cx = i + 10;
item.cy = i + 20;
Lists.Add(item);
}
for(int i = 1; i < 9; i++){
Lists[i].prev = Lists[i - 1];
Lists[i].next = Lists[i + 1];
}
Linked temp;
temp = Lists[0];
<= Here I get a program crash with diagnostic Invalid Address specified to RtlValidateHeap(...,...). And the program stops at the first delete in the default destructor of the Linked class. If I remove everything from there, then the same error (not sure if the address is the same) is on the first delete statement in the operator=. What am I doing wrong? Any help will be appreciated.