class IndexItem{
public:
IndexItem();
IndexItem(std::string w, int p, int l, int pos);
IndexItem(const IndexItem& ii);
~IndexItem();
private:
std::string word;
int page;
int line;
int position;
};
#include "IndexItem.h"
#include <string>
#include <iostream>
IndexItem::IndexItem() {
//initiates the word-sting with an empty string and the index-values with 0
word="";
page=line=position=0;
}
IndexItem::IndexItem(std::string w, int p, int l, int pos){
//initiates the word-string with the w-string and the index-values with given values
word=w;
page=p;
line=l;
position=pos;
}
IndexItem::IndexItem(const IndexItem& ii){
//copy the ii-values to this-object
word=ii.word;
page=ii.page;
line=ii.line;
position=ii.position;
}
IndexItem::~IndexItem(){};
}
Now I'm having trouble dynamically declaring and deleting these objects.
Excerpt from main.cpp
1 2 3 4 5 6
IndexItem* a=new IndexItem("Test",4,8,9);
TreeElement* i=new TreeElement(*a);
// This next line is giving trouble
delete &(*i).data;
delete a;
delete i;
I already figured out "&(*i).data" and "a" aren't the same pointers, but I don't know why. I think it has something to do with the "reference variables" (const IndexItem&) that are being used in the copy constructor of IndexElement.
I'm not getting an error, but I have memory leaks...
Important: I'm not allowed to change the header files IndexItem.h and TreeElement.h.
Line 4 may be causing the problem. It is like trying to delete a fragment of *i.
Note that i->data and *a are separate objects in memory. Your IndexItem copy constructor creates a separate instance of an IndexItem from the instance passed for it to copy from.
You ought to be able to delete a then continue using i.
What do you get if you just remove line 4?
Your deleting data which isn't declared as a pointer. TreeElement* i=new TreeElement(*a); passes a copy of a not a pointer. "Remove this delete &(*i).data;