delete operator

Even after using delete operator, it is printing the value of 4th person,then what is the use of delete operator?


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
#include<iostream>
using namespace std;
class person
{
protected:
	char name[40];
public:
	void setName()
	{
		cout<<"Enter name: ";
		cin>>name;
	}
	void printname()
	{
		cout<<"\n    Name is: "<<name;
	}
};
int main()
{
	person* persptr[100];
	int n=0;
	char choice;
	do
	{
		persptr[n]=new person;
		persptr[n]->setName();
		n++;
		cout<<"Enter another(y/n)?";
		cin>>choice;
	}while(choice=='y');
	for(int j=0;j<n;j++)
	{
		cout<<"\nPerson number "<<j+1;
		persptr[j]->printname();
	}
	cout<<endl;
	delete[] *persptr;
	cout<<"After deleting..\n, 4th person is: ";
	persptr[3]->printname();
	return 0;
}

and the output is:
Enter name: Tushar
Enter another(y/n)?y
Enter name: Gaurav
Enter another(y/n)?y
Enter name: Saurav
Enter another(y/n)?y
Enter name: Suvam
Enter another(y/n)?n

Person number 1
    Name is: Tushar
Person number 2
    Name is: Gaurav
Person number 3
    Name is: Saurav
Person number 4
    Name is: Suvam
After deleting..
, 4th person is: 
    Name is: Suvam
Last edited on
> what is the use of delete operator?
it informs that you release that memory, now other programs may use it.


By the way, you are using it wrong.
If allocated with new use delete
If allocated with new[] use delete[]
You also may need to delete every "new person" one by one with a loop, though I am not sure if this is the problem.

Also "delete [] *persptr;" might be wrong. try "delete [] persptr;" (without a star)
Last edited on
there is no persptr = new [some_number]; in the code. That memory was not new[] so it must not be delete[]
Even on using delete at the place of delete[],it is giving same output.
delete isn't obliged by the C++ standard to change the contents of the memory being pointed to by the pointer.

As ne555 already said, the purpose of delete is to specify that the memory being pointed to is now available to be reused.
Thankyou all,
I got it..
Topic archived. No new replies allowed.