Creating an object

If a class has a constructor it is executed when an object of that class is created. This constructor typically initializes the state of the object. Foundation Classes' constructors often have mandatory positional parameters that the programmer must provide at object creation time.

C++ objects can be created in one of two ways:

  1. Automatically, where the object is created on the C++ stack. For example:
    {
       ClassX     objX
       ClassY     objY(parameter1);
    }     //objects deleted here
    Here, objX and objY are automatically created on the stack. Their lifetime is limited by the context in which they were created; when they go out of scope they are automatically deleted (that is, their destructors run and their storage is released).
  2. Dynamically, where the object is created on the C++ heap. For example:
    {
       ClassX*   pObjX = new ClassX;
       ClassY*   pObjY = new ClassY(parameter1);
    }     //objects NOT deleted here
    Here we deal with pointers to objects instead of the objects themselves. The lifetime of the object outlives the scope in which it was created. In the above sample the pointers (pObjX and pObjY) are 'lost' as they go out of scope but the objects they pointed to still exist! The objects exist until they are explicitly deleted as shown here:
    {
       ClassX*     pObjX = new ClassX;
       ClassY*     pObjY = new ClassY(parameter1);
       
    ·
    ·
    ·
    pObjX->method1(); pObjY->method2();
    ·
    ·
    ·
    delete pObjX; delete pObjY; }

Most of the samples in this book use automatic storage. You are advised to use automatic storage, because you do not have remember to explicitly delete objects, but you are free to use either style for CICS® C++ Foundation Class programs. For more information on Foundation Classes and storage management see Storage management.

[[ Contents Previous Page | Next Page Index ]]