Initialization list

from Wikipedia, the free encyclopedia

The initialization list is a specialty of the C ++ programming language . It occurs exclusively in constructors and has the task of regulating the construction of ancestor classes, embedded elements and references.

background

In contrast to C , where you can declare a variable without worrying about its initialization first, in C ++ there are cases in which an immediate initialization is necessary:

  • In C ++ it is possible to make variables immutable by declaring them. This is done by prefixing the keyword const . However, you have to assign a value to such a variable with the declaration.
  • In C ++, references are called - to put it simply - pointers that can never be null; an object or an already existing reference must be assigned to them at the time of declaration.
  • Classes can be designed by their developers in such a way that they have to receive initialization values ​​for the construction of objects. An example would be a class Fraction , where you want to make sure from the beginning that there is no zero in the denominator, this can be achieved in C ++ by means of a constructor (using exceptions ).

If such restrictive declarations take place in a class definition (inheritance relationship, element declaration), the definition of the corresponding initialization values ​​is postponed to the time of construction (a constructor must be defined). Before the beginning of the constructor body, basic classes and constants or reference elements are initialized in the form of a list.

example

Class A has

  • a base class B (which defines a constructor)
  • an element of class E (which defines a constructor)
  • a constant element c
  • a reference element r

which must be supplied with initialization values ​​via the initialization list - highlighted in yellow in the code example.

class B
{
public:
    // Der Compiler erkennt automatisch, dass mit b(b) die Elementvariable b
    //  mit dem Parameter b initialisiert werden soll. Dieser Mechanismus
    //  heißt argument dependent name lookup.
    B( int b ) : b( b ) {}

    int b;
};

class E
{
public:
        E( int ein_e ) : e( ein_e ) {}

    int e;
};

class A : public B: public C: public D: public E:
{
public:
    A( int b, int ein_e, int ein_c, int& ein_r ): 
       B(b), e(ein_e), c(ein_c), r(ein_r) 
       {}

    E e;
    const int c;
    int& r;
};