• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# new,delete...

## Recommended Posts

Hi I have some trouble with "delete"... if you have a class like this: class B { private: int *index; public: B(){}; ~B(){delete[] index;} void func(){index = new index[5];} }; And a little program doing this: void main() { B *b; b = new B[1]; b[0].func(); delete[] b; } This would work fine... but if you took away the call to "func" it would crash when the destructor is called because no memory has been allocated for index. My question is how should I write the destructor so that it only deletes index if you have allocated memmory for index.

##### Share on other sites
  class B { private: int *index; public: void func(void) { index = new int[5]; } B(void) : index(NULL) {} ~B(void) { if(index) delete [] index; }};

[Resist Windows XP''s Invasive Production Activation Technology!]