Deleting object

I have an array of objects, and one of my functions is to add a new object into this array.

My function creates a temp object, which stores all the values, and then places this temp object into the array.

How do I delete this temp object?

I tried delete &x, and there are no errors but is this the correct method?

for example, this function checkReturn goes through the All array, finds the right ID, and then copies this object and places it into the checkIn array.

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
void checkReturn(const Patient *all, Patient *&checkIn, int &count, int size)
{
	int checkID;
	int askIDcount = 0;
	char choice;
	Patient temp2;
	cout << "ID of returning patient: " << endl;
	cin >> checkID;
	
	cout << "Checking if patient exists in current directory..." << endl;
		for (int i = 0; i < size; i++)
			{
				if (checkID == all[i].getID) //if found in all patients 
				{
					temp2 = all[i]; //move found patient to temp patient
					cout << "Checking in patient!!!" << endl;
					addNewEntry(checkIn, temp2, count, size); //adds patient into array of checkin
					delete &temp2;
					return; //if found, return from function
				}
				else
				{
					cout << i << "..." << endl;
				}
			}
		cout << "The given ID did not find any matches...\nReturning to main menu... " << endl;
		delete &temp2;
}


As you can see, I create a temp2 object which is placed into the array, and then I'm trying to delete temp2 as I don't need it anymore
Last edited on
You should only use delete to destroy objects that has been created with new.

Local variables are destroyed automatically when they go out of scope. temp2 goes out of scope when the function ends so you don't need to do anything.

Do you really have to create a temp variable here? Can't you just pass the array element to the function directly?

 
addNewEntry(checkIn, all[i], count, size);
Ah ok thats what I thought, variables that go out of scope get deleted automatically, thanks for clarifying!

And yeah I could have done that, my code was done in a hurry thank you for pointing that out
Topic archived. No new replies allowed.