Click here to Skip to main content
15,910,980 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C++
class Linked
{
public:
 Linked();
 virtual ~Linked()
 Linked(const Linked& cap);
 const Linked& operator=(Linked& cap);

 Linked *prev;
 Linked *next;
 CString Name;
 CPoint  Position;
}

.cpp

C++
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
C++
....
 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];
 }
// Now everything is OK so far. Then I do this
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.
Posted
Comments
xumepoc 29-Oct-12 10:30am    
Any One? :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900