Constructors and Destructors

from Wikipedia, the free encyclopedia

In programming, special procedures or methods that are called when creating or resolving objects and variables are called constructors and destructors (also called ctor or dtor for short ) . Constructors can be given parameters , while destructors usually have no arguments.

Constructors and destructors preserve the appearance of the atomicity of the creation or the removal. At the same time, the rules for creating and resolving variables of the relevant type can already be formulated during the declaration by passing certain parameters.

Constructors and destructors appear in some object-oriented programming languages , but they are a concept that is independent of object-oriented programming (OOP) and is neither a prerequisite for OOP nor is it restricted to OOP. For example, constructors and destructors also appear in procedural programming languages .

Constructors

The task of constructors is to bring objects into a defined initial state and thus reserve the required resources , provided that they are already known at the time the object is created.

Constructor types

nullary constructor is a constructor with no parameters :

class MyClass
{
    MyClass()
}

In the Java programming language , a class that does not have an explicit constructor is implicitly provided with a parameterless constructor (default constructor).

A copy constructor is used to create an object copy and has its own object type as a parameter (compare shallow copy vs. deep copy ):

class MyClass
{
    MyClass(MyClass object) { }
}

A forwarding constructor (also called constructor forwarding ) passes the parameters to another constructor and uses default values ​​for the missing parameters. This is particularly relevant for programming languages that do not support standard values ​​(e.g. Java ). This construct is to be distinguished from an initialization list , in which values ​​are actually set, while the forwarding constructor only passes values.

class MyClass
{
    MyClass(int value): this(value, 0) { }
    MyClass(int value1, int value2) { }
}

Examples

Java

class Beispiel
{
    // Konstruktor ohne Parameter
    public Beispiel() { }

    // Konstruktor mit Parameter
    public Beispiel(String text)
    {
        System.out.println(text);
    }
    
    // Hauptmethode
    public static void main(String[] args)
    {
        Beispiel beispiel1 = new Beispiel();  // Keine Ausgabe
        Beispiel beispiel2 = new Beispiel("Zweiter Konstruktor");  // Ausgabe: Zweiter Konstruktor
    }
}

C ++

class Beispiel
{
public:
    // Konstruktor ohne Parameter
    Beispiel() { }
   
    // Konstruktor mit Parameter
    Beispiel(int i)
    {
        std::cout << i << std::endl; 
    }
};

C #

class Beispiel
{
	// Konstruktor ohne Parameter, der den anderen Konstruktor mit this(..., ...) aufruft
	public Beispiel() : this("Heute ist der ", DateTime.Today)
	{
	}
	
	// Konstruktor mit zwei Parametern
	public Beispiel(string text, DateTime datum)
	{
		Console.WriteLine(text + datum.ToShortDateString());
	}
	
    // Hauptmethode
	public static void Main(string[] args)
	{
		Beispiel beispiel1 = new Beispiel("Morgen ist der ", DateTime.Today.AddDays(1));
		// Aufruf des ersten Konstruktors
		// Ausgabe: Morgen ist der {dd.MM.yyyy}
		
		Beispiel beispiel2 = new Beispiel();
		// Aufruf des zweiten Konstruktors
		// Ausgabe: Heute ist der {dd.MM.yyyy}
	}
}

PHP

/**
 * @see: http://php.net/manual/language.oop5.decon.php
 */
class Foobar
{
    // Konstruktor mit Parameter und Defaultwert
    public function __construct($text = null)
    {
        if ($text !== null)
        {
            echo $text;
        }
    }

    public function Foobar()
    {
        // wird in PHP 5.3.0-5.3.2 als Konstruktor behandelt
        // wird in PHP 5.3.3 und höher als reguläre Methode behandelt
    }
}

Destructors

Destructors are usually responsible for releasing resources used by the object . Programming languages such as C ++ guarantee the execution of destructors whenever the scope of the variable is left (see RAII ) if the principle is maintained that a destructor does not control flow by throwing an exception ( throw interrupts). Therefore, sometimes constructors and destructors are used, the sole purpose of which is to ensure the correct balance of resources in the given context, in C ++ for example with the class template unique_ptr.

Difference to finalization

Programming languages such as Java or Python and the .NET development platform use the concept of finalization , an alternative to destructors , in which cleanup work is not carried out at the earliest possible point in time, but only with the next run of the automatic garbage collection . The procedure that does this is called the finalization routine or finalizer. Finalizers have some limitations compared to destructors. For example, finalizers are generally not allowed to refer to other objects, as these may already have been broken down.

See also

literature