Object Lifetime - Creating Objects

Creating Objects

In typical case, the process is as follows:

  • calculate the size of an object - the size is mostly the same as that of the class but can vary. When the object in question is not derived from a class, but from a prototype instead, the size of an object is usually that of the internal data structure (a hash for instance) that holds its slots.
  • allocation - allocating memory space with the size of an object plus the growth later, if possible to know in advance
  • binding methods - this is usually either left to the class of the object, or is resolved at dispatch time, but nevertheless it is possible that some object models bind methods at creation time.
  • calling an initializing code (namely, constructor) of superclass
  • calling an initializing code of class being created

Those tasks can be completed at once but are sometimes left unfinished and the order of the tasks can vary and can cause several strange behaviors. For example, in multi-inheritance, which initializing code should be called first is a difficult question to answer. However, superclass constructors should be called before subclass constructors.

It is a complex problem to create each object as an element of an array. Some languages (e.g. C++) leave this to programmers.

Handling exceptions in the midst of creation of an object is particularly problematic because usually the implementation of throwing exceptions relies on valid object states. For instance, there is no way to allocate a new space for an exception object when the allocation of an object failed before that due to a lack of free space on the memory. Due to this, implementations of OO languages should provide mechanisms to allow raising exceptions even when there is short supply of resources, and programmers or the type system should ensure that their code is exception-safe. Note that propagating an exception is likely to free resources (rather than allocate them). However, in object oriented programming, object construction may always fail, because constructing an object should establish the class invariants, which are often not valid for every combination of constructor arguments. Thus, constructors can always raise exceptions.

The abstract factory pattern is a way to decouple a particular implementation of an object from code for the creation of such an object.

Read more about this topic:  Object Lifetime

Famous quotes containing the words creating and/or objects:

    I have heard it said
    There is an art which in their piedness shares
    With great creating nature.
    William Shakespeare (1564–1616)

    Where then shall hope and fear their objects find?
    John Ashbery (b. 1927)