Archived

This topic is now archived and is closed to further replies.

shakazed

Aw p0lice help me with the "new" keyword

Recommended Posts

Guest Anonymous Poster
did you know there is a forum for beginners?

new creates memory that you don''t want to go out of scope at the end of a function. If you''re used to C then its equivalent to malloc to allocate memory. It also calls the constructors for your objects so that you can perform any specific initialisation for your class.

Share this post


Link to post
Share on other sites
quote:
Original post by civguy
Learn from a book.


Very helpful. Very.

The new keyword is used to reserve dynamic memory, like malloc(). The advantage is that instead of specifying a size and typecasting it into whatever you want to use it for, you specify the type and get a pointer to the reserved memory, already pre-formatted for you into ints, floats or whatnot without having to typecast.

Though you should''ve asked this in the beginner forum. It''s a rather basic concept

Share this post


Link to post
Share on other sites
quote:

The new keyword is used to reserve dynamic memory, like malloc(). The advantage is that instead of specifying a size and typecasting it into whatever you want to use it for, you specify the type and get a pointer to the reserved memory, already pre-formatted for you into ints, floats or whatnot without having to typecast.


You forgot the most important difference: new will call the class constructor on the aquired raw memory, basically constructing the object. The counterpart, delete, operates like free(), but will call the destructors first.

Conclusion: if you''re coding in C++, always use new/delete. You might still use malloc() on POD, or use placement new, but those are advanced usage.

BTW, moved to beginner forum.

Share this post


Link to post
Share on other sites