Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Object Instantiation

Status
Not open for further replies.

nicasa

Programmer
Feb 3, 2003
54
ES
HI there,

Essentially a C programmer, I would like to know when an object should be instsantiated on the stack and when on the free store.

eg for class fred, we can create objects as follows:

fred myobject;

// use myobject
// myobject.function();

OR

fred myobject = new fred();

// use myobject
// myobject->function();

Can anyone giove some examples...


Thanks,


bigSteve
 
class fred
{ ... };

...fred MyObject; - static instantiation - MyObject will reside on stack. When code exits the code-block (i.e. function) where MyObject is instantiated, MyObject will be deleted.

...fred * MyObject = new fred(); (watch for asteriks!)- dynamic instantiation - New fred-object is created on heap (with *MyObject as a pointer to that instance)and is not related to any particular part of code. It will live there as long as your application is running. You will have to explicitly destroy this : delete MyObject.

How to know when to use any particular method? Well, you can't tell - it depends on many things, but just remember that objects created on stack inside some function will be deleted from stack as soon as your function returns.

P.S.
Since this is C++Builder forum, beware that any VCL-aware object MUST BE dynamicaly created!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top