Object lifetime

In computer science, the object lifetime (or life cycle) of an object in object-oriented programming is the time between an object's creation (also known as instantiation or construction) till the object is no longer used, and is destructed or freed.

In object-oriented (OO) programming, the meaning of creating objects is far more subtle than simple allocating of spaces for variables. First, this is due to the fact that, in the OO paradigm, the lifetime of each object tends to vary more widely than in the case in conventional programming. There are a lot of subtle questions, such as should the object be considered alive in the process of creation, or about the order of calling initializing code. In some sense, the creation can happen before the beginning of the program when objects are placed in a global scope.

Contents

Creating objects

In a 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.
  • allocation - allocating memory space with the size of an object plus the growth later, if possible to know in advance
  • binding methods
  • 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 how to create each object as element of an array. Some languages (e.g. C++) leave this to programmers.

Handing exceptions in the midst of creation of an object is particularly problematic because usually the implentation 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 a object.

Creation methods

The way to create objects varies across languages. In some class-based languages, a special method known as a constructor, is responsible for validating the state of an object. Just like ordinary methods, constructors can be overloaded in order to make it so that an object can be created with different attributes specified. Also, the constructor is the only place to set the state of immutable objects. A copy constructor is a constructor which takes a (single) parameter of an existing object of the same type as the constructor's class, and returns a deep copy of the object sent as a parameter.

Other programming languages, such as Objective-C, have class methods, which can include constructor-type methods, but are not restricted to merely instantiating objects.

C++ and Java have been criticized for not providing named constructors. This can be problematic, for instance, when a programmer wants to provide ways to create a point object either from cartesian coordinate or from the polar coordinate--because both coordinates would be represented by two integers. Objective-C can circumvent this problem, in that the programmer can create a Point class, with initialization methods, for example, +newPointWithX:andY:, and +newPointWithR:andTheta:.

A constructor can also refer to a function used to create a value of a tagged union, particularly in functional languages.

Destroying objects

It is generally the case that after an object is used, it is removed from memory in order for efficiency and for other programs or more objects to take that object's place. In order for this to happen, a destruction method is called upon that object. Destroying an object will cause any references to the object to become invalid.

A destructor is a method called when an instance of a class is deleted, before the memory is deallocated. Note that in C++, a destructor can not be overloaded like a constructor can. It has to have no arguments. A destructor does not need to maintain class invariants.

In a garbage collecting language, objects are destroyed when they can no longer be reached by the running code. Examples of this are Python and Java. Python has destructors, and they are optional.

Examples

C++

class Foo
{
    // This is the prototype of the constructors
public:
    Foo(int x);
    Foo(int x, int y); // Overloaded Constructor
    Foo::Foo(const Foo &old); // Copy Constructor
    ~Foo(); // Destructor
};

Foo::Foo(int x)
{
    // This is the implementation of
    // the one-argument constructor
}

Foo::Foo(int x, int y)
{
    // This is the implementation of
    // the two-argument constructor
}

Foo::Foo(const Foo &old)
{
    // This is the implementation of
    // the copy constructor
}

Foo::~Foo()
{
    // This is the implementation of the destructor
}

int main()
{
    Foo foo(14); // call first constructor
    Foo foo2(12, 16); // call overloaded constructor
    Foo foo3(foo); // call the copy constructor
 
    return 0;
    // destructors called in backwards-order
    // here, automatically
}

Java

class Foo
{

public Foo(int x)
{
    // This is the implementation of
    // the one-argument constructor
}

public Foo(int x, int y)
{
    // This is the implementation of
    // the two-argument constructor
}

public Foo(Foo old)
{
    // This is the implementation of
    // the copy constructor
}

public static void main()
{
    Foo foo = new Foo(14); // call first constructor
    Foo foo2 = new Foo(12, 16); // call overloaded constructor
    Foo foo3 = new Foo(foo); // call the copy constructor
 
    exit(0);
    // garbage collection happens under the covers, and classes are destroyed
}

Objective-C

#import <objc/Object.h>

@interface Point : Object
{
   double x;
   double y;
}

//These are the class methods; we have declared two constructors
+ (Point *) newWithX: (double) andY: (double);
+ (Point *) newWithR: (double) andTheta: (double);

//Instance methods
- (Point *) setFirstCoord: (double);
- (Point *) setSecondCoord: (double);

/* Since Point is a subclass of the generic Object 
 * class, we already gain generic allocation and initialization
 * methods, +alloc and -init. For our specific constructors
 * we can make these from these methods we have
 * inherited.
 */
@end

@implementation Point

- (Point *) setFirstCoord: (double) new_val
{
   x = new_val;
}

- (Point *) setSecondCoord: (double) new_val
{
   y = new_val;
}

+ (Point *) newWithX: (double) x_val andY: (double) y_val
{
   //Concisely written class method to automatically allocate and 
   //perform specific initialization.
   return [[[Point alloc] setFirstCoord:x_val] setSecondCoord:y_val]; 
}

+ (Point *) newWithR: (double) r_val andTheta: (double) theta_val
{
   //Instead of performing the same as the above, we can underhandedly
   //use the same result of the previous method
   return [Point newWithX:r_val andY:theta_val];
}

@end

int
main(void)
{
   //Constructs two points, p and q.
   Point *p = [Point newWithX:4.0 andY:5.0];
   Point *q = [Point newWithR:1.0 andTheta:2.28];

   //...program text....
   
   //We're finished with p, say, so, free it.
   //If p allocates more memory for itself, may need to
   //override Object's free method in order to recursively
   //free p's memory. But this is not the case, so we can just
   [p free];

   //...more text...

   [q free];

   return 0;
 }

Python

class Socket:
    def __init__(self, remote_host):
        self.connection = connectTo(remote_host)

    def send(self):
        # send data

    def recv(self):
        # receive data

    def __del__(self):
        self.connection.close()

def f():
    s = Socket('example.com')
    s.sent('blah')
    return s.recv()
       # Socket will be closed at the next
       # garbage collection round, as all
       # references to it have been lost.

de:Konstruktoren und Destruktoren

Navigation

  • Art and Cultures
    • Art (https://academickids.com/encyclopedia/index.php/Art)
    • Architecture (https://academickids.com/encyclopedia/index.php/Architecture)
    • Cultures (https://www.academickids.com/encyclopedia/index.php/Cultures)
    • Music (https://www.academickids.com/encyclopedia/index.php/Music)
    • Musical Instruments (http://academickids.com/encyclopedia/index.php/List_of_musical_instruments)
  • Biographies (http://www.academickids.com/encyclopedia/index.php/Biographies)
  • Clipart (http://www.academickids.com/encyclopedia/index.php/Clipart)
  • Geography (http://www.academickids.com/encyclopedia/index.php/Geography)
    • Countries of the World (http://www.academickids.com/encyclopedia/index.php/Countries)
    • Maps (http://www.academickids.com/encyclopedia/index.php/Maps)
    • Flags (http://www.academickids.com/encyclopedia/index.php/Flags)
    • Continents (http://www.academickids.com/encyclopedia/index.php/Continents)
  • History (http://www.academickids.com/encyclopedia/index.php/History)
    • Ancient Civilizations (http://www.academickids.com/encyclopedia/index.php/Ancient_Civilizations)
    • Industrial Revolution (http://www.academickids.com/encyclopedia/index.php/Industrial_Revolution)
    • Middle Ages (http://www.academickids.com/encyclopedia/index.php/Middle_Ages)
    • Prehistory (http://www.academickids.com/encyclopedia/index.php/Prehistory)
    • Renaissance (http://www.academickids.com/encyclopedia/index.php/Renaissance)
    • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
    • United States (http://www.academickids.com/encyclopedia/index.php/United_States)
    • Wars (http://www.academickids.com/encyclopedia/index.php/Wars)
    • World History (http://www.academickids.com/encyclopedia/index.php/History_of_the_world)
  • Human Body (http://www.academickids.com/encyclopedia/index.php/Human_Body)
  • Mathematics (http://www.academickids.com/encyclopedia/index.php/Mathematics)
  • Reference (http://www.academickids.com/encyclopedia/index.php/Reference)
  • Science (http://www.academickids.com/encyclopedia/index.php/Science)
    • Animals (http://www.academickids.com/encyclopedia/index.php/Animals)
    • Aviation (http://www.academickids.com/encyclopedia/index.php/Aviation)
    • Dinosaurs (http://www.academickids.com/encyclopedia/index.php/Dinosaurs)
    • Earth (http://www.academickids.com/encyclopedia/index.php/Earth)
    • Inventions (http://www.academickids.com/encyclopedia/index.php/Inventions)
    • Physical Science (http://www.academickids.com/encyclopedia/index.php/Physical_Science)
    • Plants (http://www.academickids.com/encyclopedia/index.php/Plants)
    • Scientists (http://www.academickids.com/encyclopedia/index.php/Scientists)
  • Social Studies (http://www.academickids.com/encyclopedia/index.php/Social_Studies)
    • Anthropology (http://www.academickids.com/encyclopedia/index.php/Anthropology)
    • Economics (http://www.academickids.com/encyclopedia/index.php/Economics)
    • Government (http://www.academickids.com/encyclopedia/index.php/Government)
    • Religion (http://www.academickids.com/encyclopedia/index.php/Religion)
    • Holidays (http://www.academickids.com/encyclopedia/index.php/Holidays)
  • Space and Astronomy
    • Solar System (http://www.academickids.com/encyclopedia/index.php/Solar_System)
    • Planets (http://www.academickids.com/encyclopedia/index.php/Planets)
  • Sports (http://www.academickids.com/encyclopedia/index.php/Sports)
  • Timelines (http://www.academickids.com/encyclopedia/index.php/Timelines)
  • Weather (http://www.academickids.com/encyclopedia/index.php/Weather)
  • US States (http://www.academickids.com/encyclopedia/index.php/US_States)

Information

  • Home Page (http://academickids.com/encyclopedia/index.php)
  • Contact Us (http://www.academickids.com/encyclopedia/index.php/Contactus)

  • Clip Art (http://classroomclipart.com)
Toolbox
Personal tools