Aw p0lice help me with the "new" keyword

Started by
7 comments, last by shakazed 20 years, 11 months ago
Okay, I kinda learn C++ as I go on gameprogramming, but I have no idea on when I need to use the "new" keyword. When and why do I need it? Bad Monkey Productions
Advertisement
Learn from a book.
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.
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
What would the police know about programming?
Have you re-new your license and registration?
Try sending a message in a bottle.

...and that is why I believe linux must be destroyed.
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
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.
Thanks for the answers!

This topic is closed to new replies.

Advertisement