Hi!

You never call explicitely a destructor in C++.
C++ will handle carbage collection when object goes
out of scope unless you have dynamically
created the object with 'new' operator.
If you have created an object with 'new', you have to use
'delete' operator to free the object (which will call the
destructor).

Allocating Person object with new.

{
  Person *p = new Person("John");
} // memory leak! "John" stays in memory and you loose the pointer.

Declaring a variable of type Person without 'new'-operator.

{
  Person p("Joe");
} // "Joe" is freed at here by C++'s carbage collector

I hope this information is correct and clarifies this thing :)

Sincerely

    Jukka Aittokallio
    [EMAIL PROTECTED]


holotko wrote:

> 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?
>
> 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.
>
> 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.

Reply via email to