C++ objects

This section describes how to create, use, and delete objects. In this context, an object is an instance of a class. An object cannot be an instance of a base or abstract base class. It is possible to create objects of all the concrete (non-base) classes described in the foundation class reference information.

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.

    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.

    Example:

    {
    ClassX* pObjX = new ClassX;
    ClassY* pObjY = new ClassY(parameter1);
    } //objects NOT deleted here
    Here you 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 previous 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 information 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.

Using an object

Any of the class public methods can be called on an object of that class. The following example creates object obj and then calls method doSomething on it:
ClassY obj("TEMP1234");
obj.doSomething();
Alternatively, you can do this using dynamic object creation:
ClassY* pObj = new ClassY("parameter1");
pObj->doSomething();

Deleting an object

When an object is destroyed its destructor function, which has the same name as the class preceded with ~(tilde), is automatically called. (You cannot call the destructor explicitly).

If the object was created automatically it is automatically destroyed when it goes out of scope.

If the object was created dynamically it exists until an explicit delete operator is used.