How to delete all new dynamic variables at once?

Ok, for a brief explanation, this program is to simulate a train. You can add train cars, detach them, and move between train cars. I have no problem with that. I want to delete all dynamically created train variables after the user quits the loop. How do I do so? I tried adding a destructor to my class with "delete next;" and "delete previous;" but the program had a run time error. I am new to pointers and dynamic memory and I want to know how to do that. I will include main() and the add() function where I add the new variaables. Thx for the help!!

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <iostream>

using namespace std;

class train
{
	public:
	train(string);
	~train();
	string getName();
	train* nextTrain();
	train* previousTrain();
	bool hasNext();
	bool hasPrevious();
	void add(string);
	void detach();
	
	private:
	string name;
	train* next;
	train* previous;
};

train::train(string str)
{
	name = str;
	next = NULL;
	previous = NULL;
}

train::~train()
{
    delete this -> previous;
}
	
string train::getName()
{
	return name;
}

train* train::nextTrain()
{
	return next;
}

train* train::previousTrain()
{
	return previous;
}

bool train::hasNext()
{
	return next;
}

bool train::hasPrevious()
{
	return previous;
}

void train::add(string str)
{
	train* temp = new train(str);
	
	temp -> next = this;
	temp -> previous = previous;
	
	if(previous)
	{
		previous -> next = temp;
	}
	
	previous = temp;
}

void train::detach()
{
	if (!previous)
	{
		return;
	}
	
	if (!(previous -> previous))
	{
		previous = NULL;
	}
	
	else if (previous -> previous)
	{
		previous -> previous -> next = this;
		previous = previous -> previous;
	}
}
	
int main()
{
	train engine = train("Engine");
	train* current = &engine;
	string choice;
	do
	{
		if(current -> hasNext())
		{
			cout << "Next train: " << current -> nextTrain() -> getName() << endl;
		}
		
		cout << "Current train: " << current -> getName() << endl;

		if(current -> hasPrevious())
		{
			cout << "Previous train: " << current -> previousTrain() -> getName() << endl;
		}
		
		cout << "Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, (d)etach a train, or (q)uit?\n";
		getline(cin,choice);
		
		if(tolower(choice[0]) == 'n' && current -> hasNext())
		{
			current = current -> nextTrain();
		}
		else if(tolower(choice[0]) == 'p' && current -> hasPrevious())
		{
			current = current -> previousTrain();
		}
		else if(tolower(choice[0]) == 'a')
		{
			cout << "Which train is this?\n";
			string name;
			getline(cin, name);
			current->add(name);
		}	
		else if(tolower(choice[0]) == 'd')
		{
			current -> detach();
		}
		else if(tolower(choice[0]) == 'q')
		{
			 current = &engine;
                         delete current;
                }
		
   }while(tolower(choice[0]) != 'q');
  
}

Last edited on
I tried adding a destructor to my class with "delete next;" and "delete previous;" but the program had a run time error.
Consider this. Suppose you have a train with two cars, 1 and 2. Car 1's previous is nullptr and its next is car 2, while car 2's previous is car 1 and its next is nullptr.
Suppose your destructor looks like this:
1
2
3
4
train::~train(){
    delete this->previous;
    delete this->next;
}
Finally, suppose that you start by deleting car 1.

Then the order of operations will be this:
delete car1->previous; // car1->previous == nullptr, so this does nothing
delete car1->next; // car1->next == car2, so move into car2's destructor
delete car2->previous; // car2->previous == car1, so move into car1's destructor
delete car1->previous; // car1->previous == nullptr, so this does nothing
delete car1->next; // car1->next == car2, so move into car2's destructor
delete car2->previous; // car2->previous == car1, so move into car1's destructor

And so on, until the stack runs out.
Can you figure out how to fix this?
Oh so am I basically not deleting anything while doing that? I am going through an infinite loop?

so if I do

1
2
3
4
train::~train()
{
    delete this -> previous;
}


and if I start with deleting the first train car (next is nullptr), will it delete all?

Edit: It does not work :( Error again. Why?
Last edited on
What error are you getting?
> I will include main() and the add() function where I add the new variables.
¿didn't occur you to include the function where you try to remove them?

> Suppose your destructor looks like this:
¡Let's start the mind reading!

> It does not work :( Error again. Why?
I guess it's because of your shallow copy constructor.

By the way, you should differentiate a `node' from a `list'.
Okay, I have included my whole program. When I execute this, the computer gave an error message after a few seconds saying my program stopped working due to something, which means something is wrong in my code.

And the main problem I am having here is to remove all the train cars after the user quits the loop. I want to keep all the built train cars while the user is still playing. Isn't it right? I have no idea how to keep track of all my new train cars and delete them.
Use std::unqiue_ptr instead, it deletes itself, so no need for destructors or freeing memory.
I want to learn how to delete all the boxes manually as I am new to this topic. I want to know how it works before I take shortcuts
> train engine = train("Engine");
that would use the copy constructor.
Your copy constructor is ill-formed, as it performs a shallow copy and so both objects would try to delete the same pointer.

However, because the train is empty, you've got no issue there. Still, that needs to be fixed.


1
2
3
4
5
		else if(tolower(choice[0]) == 'q')
		{
			 current = &engine;
                         delete current; //remove this line
                }
`engine' was not dynamic allocated, you should not delete it.
`engine' would be destroyed when it goes out of scope, at the end of main().


`train::detach()' is leaking memory, you never delete the previous node.


> saying my program stopped working due to something, which means something is
> wrong in my code.
the debugger is your friend.
at least, it would point the line where it crashed.

If you still have issues, provide an example input so we can reproduce your problem.
Topic archived. No new replies allowed.