Object lifetime
Encyclopedia
In computer science
Computer science
Computer science or computing science is the study of the theoretical foundations of information and computation and of practical techniques for their implementation and application in computer systems...

, the object lifetime (or life cycle) of an object in object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 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 programming (OOP), the meaning of creating objects is far more subtle than simple allocating of spaces for variables. First, this is because, in the OOP paradigm, the lifetime of each object tends to vary more widely than in the case in conventional programming. There are many subtle questions, including whether the object be considered alive in the process of creation, and concerning 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.

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
    Class (computer science)
    In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

     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
    Name binding
    In programming languages, name binding is the association of objects with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-object bindings as a service and notation for the programmer is implemented...

     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
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

 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
Abstract factory pattern
The abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the...

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

Creation methods

The way to create objects varies across languages. In some class-based languages, a special method known as a constructor
Constructor (computer science)
In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...

, is responsible for validating the state of an object. Just like ordinary methods, constructors can be overloaded
Method overloading
Function overloading or method overloading is a feature found in various programming languages such as Ada, C#, VB.NET, C++, D and Java that allows the creation of several methods with the same name which differ from each other in terms of the type of the input and the type of the output of the...

 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 object
Immutable object
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created...

s. A copy constructor
Copy constructor
A copy constructor is a special constructor in the C++ programming language creating a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed , which might be followed by parameters of any type...

is a constructor which takes a (single) parameter of an existing object of the same type as the constructor's class, and returns a copy of the object sent as a parameter.

Other programming languages, such as Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

, have class methods, which can include constructor-type methods, but are not restricted to merely instantiating objects.

C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 and Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 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 which is used to create a value of a tagged union
Tagged union
In computer science, a tagged union, also called a variant, variant record, discriminated union, or disjoint union, is a data structure used to hold a value that could take on several different, but fixed types. Only one of the types can be in use at any one time, and a tag field explicitly...

, particularly in functional languages.

Destroying objects

It is generally the case that after an object is used, it is removed from memory to make room for other programs or 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 reference
Reference
Reference is derived from Middle English referren, from Middle French rèférer, from Latin referre, "to carry back", formed from the prefix re- and ferre, "to bear"...

s to the object to become invalid.

A destructor
Destructor (computer science)
In object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed...

is a method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

 called when an instance of a class is deleted, before the memory
Computer storage
Computer data storage, often called storage or memory, refers to computer components and recording media that retain digital data. Data storage is one of the core functions and fundamental components of computers....

 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 invariant
Class invariant
In computer programming, specifically object-oriented programming, a class invariant is an invariant used to constrain objects of a class. Methods of the class should preserve the invariant. The class invariant constrains the state stored in the object....

s.

In garbage collecting
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...

 languages, objects may be destroyed when they can no longer be reached by the running code. Examples of this are Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 and Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

. Python has destructors, and they are optional. In many garbage collecting languages, finalizer
Finalizer
In object-oriented programming languages that use garbage collection, a finalizer is a special method that is executed when an object is garbage collected. It is similar in function to a destructor...

s
(which are called before an object is garbage-collected) are used instead of destructors, since the point of garbage-collection is not predictable in these languages. Example of these include Java and Ruby.

C++


class Foo
{
// This is the prototype of the constructors
public:
Foo(int x);
Foo(int x, int y); // Overloaded Constructor
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(String[] args)
{
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
// garbage collection happens under the covers, and classes are destroyed
}
}

C#


namespace ObjectLifeTime
{
class Foo
{
public Foo
{
// This is the implementation of
// default constructor
}

public Foo(int x)
{
// This is the implementation of
// the one-argument constructor
}
~Foo
{
// This is the implementation of
// the destructor
}
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(string[] args)
{
Foo defaultfoo = new Foo; // call default constructor
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

}
}
}

Objective-C

  1. import


@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 f:
s = Socket('example.com')
s.send('test')
return s.recv

Socket will be closed at the next garbage collection round, as all references to it have been lost.

See also

  • Resource Acquisition Is Initialization
    Resource Acquisition Is Initialization
    Resource Acquisition Is Initialization is a programming idiom used in several object-oriented languages like C++, D and Ada. The technique was invented by Bjarne Stroustrup to deal with resource deallocation in C++...

    (RAII), an approach to managing object lifetime
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK