> 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?
There are two situations. One is that the value is created on the
stack inside a function call. Global variables are similar except that
they don't get deleted until main() terminates. Thus, you can do:
void my_func()
{
Foo foo;
/* do some stuff here */
} /* Foo gets deallocated */
Upon reaching the close bracket of the function, foo gets deleted
automatically, and any relevant destructors are called.
This is true of *any* pair of brackets; they don't have to be
a function. For example:
void my_func(bool do_it)
{
if (do_it)
{
Foo foo;
/* some stuff */
} /* foo gets deallocated */
/* foo is _not_ valid here */
}
This is what is called "scoping". The scope of foo in the function above
is the interior of the if (do_it) block of code. In the other example,
the scope is the body of my_func.
Now, if you allocate a Foo on the *heap* (that is, with the 'new' keyword),
you have to keep track of the memory yourself. You're already doing this
within the Foo class; it has a character array called "word" which it
explicitly allocates space for, and then explictly deallocates when the
object gets destoryed.
In the exact same way, any Foo's created with 'new' need to be explictly
tracked. For example:
void my_func()
{
Foo *foo = new Foo;
/* code */
delete foo;
} /* Foo is NOT automatically deallocated here */
This can, of course, easily lead to memory "leaks" where space is allocated
but no pointer is kept to the location.
Foo *my_func()
{
return new Foo;
}
void other_func()
{
my_func();
}
If other_func() gets called, it's a memory leak. No one is keeping track
of the allocated Foo object, and it is now in your program's memory space
with no way to address it.