Dynamic memory allocation of object within object

Hello,

I'm a beginner and tried to find on google what I am doing wrong...

I'm using Microsoft Visual C++ 2008 express edition. I execute my program in debug mode.

I have two classes: "TreeElement" and "IndexItem". A TreeElement contains an IndexItem. Shortened header files:

TreeElement.h
1
2
3
4
5
6
7
8
9
10
class TreeElement {
#include "IndexItem.h"

public:
	TreeElement(): left(NULL), right(NULL), parent(NULL){}
	TreeElement(const IndexItem& element) : left(NULL), right(NULL), parent(NULL), data(element) {}

	TreeElement *left, *right, *parent;
	IndexItem data;
};


IndexItem.h
1
2
3
4
5
6
7
8
9
10
11
12
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;
};


Implementation of IndexItem:
IndexItem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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.

Thanks in advance,
Krulle from Belgium.
Last edited on
closed account (D80DSL3A)
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;
Thanks for your response fun2code and naraku9333. I understand I did something (horribly) wrong. Problem solved.
Topic archived. No new replies allowed.