>
>
> Being spoiled by Java's garbage collector leads me to this quick
> question again concerning constructors in C++.
>
> If I allocate memory via "new" using a constructor
>
> i.e.
>
> class Foo
> {
> Foo()
> { word = new char[LENGTH + 1]; }
>
> ~Foo()
> { delete word; }
>
> ...
> }
>
> When I create an object of class Foo memory will be allocated for the
> char buffer "word". Now when the object is no longer needed must I
> make an explicit call to the destructor ~Foo() to destroy the object
> and subsequently call "delete", or, is the destructor somehow called
> automatically when the object is no longer needed,i.e. outside of
> it's scope?
If you allocate a 'Foo' off the stack, like:
Foo myFoo;
then it will be automaticly destroyed as soon as the function
in which it was created ends (it will be destroyed automagicly).
Destruction results in the destructor (~Foo()) being called, and the
memory allocated to Foo (in this case off the stack) being released.
In short, you don't have to do anything.
HOWEVER, you need to change your destructor so that it looks like this:
{delete [] word;}
In short: if your call to new uses [], so should your call to delete.
Notice how you don't need to put a length in the [] durring a
delete. C++ just need to know it's an array you're deleting.
It will deal with the length.
>
> Even in Java there are times when it is up to you to destroy an object
> and/or free memory used for that object, depending on how the object
> is/was created and an method equivalent of a destructor is required...
> The garbage collector is not always adequate.
>
In C/C++:
If you created it off the stack, it will handle the cleanup.
If you created it dynamically, (usually new/malloc()) you
must clean it up.
> Thanks...
>
> Sincerely,
>
> /John <[EMAIL PROTECTED]>
>
>
> --
> email: [EMAIL PROTECTED]
> Local mailserver <landreau.ruffe.edu> , remote <ns.computer.net>
>
> There is a great alternative to war, it's called Peace.
>