Sign in to follow this  

Creating objects

This topic is 3868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Quote:
Original post by Zotoaster
Just a quick question, I just wanted to know what the difference was between:

myClass myObject;

and

myClass* myObject = new myClass;



Thank you :)


The first one creates an object on the stack, which mean that it will be destroyed when the stack will be rewinded - or when the current block in which the object is defined ends.

Exemple:
void f()
{
my_class object_1;

if (some_condition)
{
my_class object_2;
// ...
} // <-- object_2 is destroyed here
// ..
// ..
} // <-- object_! is automatically destroyed here

Such objects are said to have an automatic storage duration - you don't request their destruction explicitely, the only thing you have to do is to follow the rules that are described in the C++ standard (and in most major C++ books out there).

The other has a dynamic storage duration. You have to explicitely destroy it by calling operator delete.

And I must log off, because the bar where I am is closing [sad]

Share this post


Link to post
Share on other sites
That clears up alot. Thanks :)

But is there any advantage of the second over the first? I mean, if you have the choice, why would you want to have to worry about having to delete it?

*waits for you to get home from the bar... assuming you have drived safely* :P

Share this post


Link to post
Share on other sites
There are several reasons to store objects on heap space (new allocates heap space and gives back a pointer to it).
One major reason is that the stack is limited in size, its size depends on the system you are running it. Some common stack sizes on modern systems are 1-2MB. As you can see that is hardly enough space to store all your program resources on.

Another reason is something that sounds only as an advantage first, the object gets destroyed when running out of scope. There are a lot of situation where you don't want that behaviour, instead you want to create an object in a function and pass the pointer of it to another function/object and you rely on it that the space you are referring to is actually the object data and not a random junk of memory.

Share this post


Link to post
Share on other sites

This topic is 3868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this