C++ Question
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~
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.
People fear what they don''t understand, hate what they can''t conquer!
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~
Thanks
~Steve~
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement