Click to See Complete Forum and Search --> : delete class question
elimin8tor
June 15th, 2002, 11:14 AM
Hi, if I have a class A
class A
{
public:
char *pchar;
};
A *pA;
int main()
{
pA = new A[4];
pA[0].pchar = new char[256];
delete[] A;
return 0;
}
is that good enough?
Or do I have to explicitly delete pchar?
NigelQ
June 15th, 2002, 02:58 PM
You have to explicitly call
delete [] pA[0].pchar
Hope this helps,
- Nigel
Bob Davis
June 15th, 2002, 10:56 PM
This is a place where a destructor would be in order. Your A class would become:
class A
{
public:
A();
~A();
char *pchar;
};
A::~A()
{
if (pchar != NULL) delete pchar;
}
Or, if pchar would be pointing to the beginning of a string (a character array), it would be delete [] pchar. Anyway, you get the idea. When an A object goes out of scope, the destructor (~A) will be called, which in this case will deallocate the memory that pchar points to. Hope this helps.
elimin8tor
June 16th, 2002, 02:48 AM
thx Bob, works perfectly.
Graham
June 16th, 2002, 11:17 AM
One thing to note, though: you can't (or at least shouldn't) mix new with delete[] or new[] with delete. Since you have no way of enforcing one form of new over another (because of the public data member), you lay yourself open to some hard-to-find bugs. It would be much better to make the data member private and use public member functions to do the allocation - that way you control which form of new/delete you use.
Or, even better, use std::string, not char*.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.