C++ Delete operator

Hello Guys!!!
I am trying to use the DeleteMember() function but object is not deleted. I create the object with new operator. Here's the Code:
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
class User
{
      protected:
      int *ID;

      public:
      User();
      User(int *id){
      setID(id);
      }
      ~User(){};
      static void setID(){
           int ID;
           cout<<"Enter ID: ";
           cin>>ID;
           }
      void setID(int *id){
           ID=new int[strlen(id)+1];
           strcpy(ID,id);
           }
      void *getID(){
           return ID;
           }
};
class Members: public User
{
      public:
      static void DeleteMember(){
           cout<<"Deleting member information! Please wait...."<<endl;
           delete ID;
           }
};
int main()
{
      Members::DeleteMember();
    getch();
}

When i try to compile this piece of code it gaves me these errors:
In static member function `static void Members::DeleteMember()':
invalid use of member `User::ID' in static member function
from this location (Line 30)

Please help me to sort this out.....Thanks!!!
Last edited on


Why not create the function
1
2
3
4
static void DeleteMember(){
           cout<<"Deleting member information! Please wait...."<<endl;
           delete ID;
           }

inside the parent class User.

Also the pointer ID is not a static member of the class User


Static variables are created and initialised once at program startup and
continue to exist right until the program terminates.


Sorry for my bad english
Last edited on
You have a lot of errors in that code, and I don't even know why you treat a pointer to an integer as if it were a string! (lines 18 and 19). This cannot even compile, and if your compiler is compiling it, dump that compiler for one that works. Nothing good can come out of it.

As pointed out, DeleteMember() is static and cannot access ID. Also in main() you are trying to delete an object, but you never create one in the first place. The overloaded setID() that is static tries to access the ID variable that isn't static.

In a word: Bad. Read this website's tutorial on classes: http://www.cplusplus.com/doc/tutorial/classes/
Besides what other users mentioned you are trying to delete an unallocated variable (ID) inside main(). Not a good thing to do.

And besides that you are trying to delete it with the wrong command:
You are using new[] so you must use delete[] to delete it, not delete (the latter just deletes the first element of the array).

(beside others) see also:
http://www.cplusplus.com/reference/std/new/operator%20new%5B%5D/
http://www.cplusplus.com/reference/std/new/operator%20delete%5B%5D/
Topic archived. No new replies allowed.