[prog] C++ object creation

Kathryn Hogg kjh at flyballdogs.com
Tue May 27 16:34:55 EST 2003


ed orphan said:
> There seems to be two ways to create
> an object with C++.
> One is by using the new command along
> with a pointer:
> MyClass * MyClassPointer = new MyClass;
> and the other is much simpler:
> MyClass MyClassObject;
>  I know that the method using new creates
> dynamically allocated memory for the object.
> So, when you do not use new, what kind
> of memory ( if any ) is used?

If you have a variable declared in function, it will most likely be
allocated on the stack for most modern machines.

> I like using  MyClass MyClassObject
> because its simple and short.
> What's the advantage of using new to
> create a new object? Is using new necsessary
> for certain situations, or is it just another way
> to do the same thing?

They are most certainly not doing the same thing.  When an object is
declared as a local variable, it is destroyed when the variable goes out
of scope:

int f()
{

   MyClass MyClassObject;

   // blah blah blah
   return 0;   // Before return completes, the destructor for MyClassObject
               // will be called and it will cease to exist
}

Allocating objects from the heap (aka via "new"), allows you to control
their lifetime. They are not deallocated until you call "delete" on them. 
This is good when you need it but can lead to memory leaks if you lose
track of pointer.

-- 
Kathryn


More information about the Programming mailing list