Archived

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

steveharper101

C++ Question

Recommended Posts

Why use the new keyword on a single object? Couldn''t you just declare a variable normally? and why is it used with classes rather than just declaring the class normally i.e CClass class; Thanks Alot ~Steve~

Share this post


Link to post
Share on other sites

Well, CClass myclass(), would be a static object which is created on the stack.

CClass * pClass = new CClass();

is a dynamically allocated object - allocated on the heap.

There is less room on the stack, the stack usually changes A LOT relative to the heap - so heap is for more permanent objects. Secondly, the heap is HUGE compared to the stack, because it is comprised of the system''s virtual memory and free RAM.

hope that helps.
Bashar.

Share this post


Link to post
Share on other sites
Thanks Alot. So if you store more perminant objects on the heap does it increase performance or something? Because there dosen''t seem much point in bothering with the new keyword unless you are declaring arrays that change in length at runtime. And your not going to be to bothered about space are you?


Thanks

~Steve~

Share this post


Link to post
Share on other sites
Static objects are initialized before main() is called, but what if one of the parameters for an object is only known after main() is called ? I guess you will need to put it in the scope of main()

void main()
{
CClass s;
}

The s is not global or static. Ofcourse you can make a default constructor but then you will need an init() function for your class or something. If you use the new you will need delete, but if you forget delete you will get a memory leak. For things on the stack destructors are called automaticaly.

I guess thats a matter of style how you want to do it.

Share this post


Link to post
Share on other sites