Initialization (programming)
In
Initialization is done either by statically embedding the value at compile time, or else by assignment at
C family of languages
Initializer
In C/C99/C++, an initializer is an optional part of a
Many find it convenient to draw a distinction between the terms "declaration" and "definition", as in the commonly seen phrase "the distinction between a declaration and definition...", implying that a declaration merely designates a data object (or function). In fact, according to the
C examples:
int i = 0;
int k[4] = {0, 1};
char tx[3] = 'a';
char ty[2] = 'f';
struct Point {int x; int y;} p = { .y = 13, .x = 7 };
C++ examples:
int i2(0);
int j[2] = {rand(), k[0]};
MyClass* xox = new MyClass(0, "zaza");
point q = {0, i + 1};
Initializer list
In C++, a constructor of a class/struct can have an initializer list within the definition but prior to the constructor body. It is important to note that when you use an initialization list, the values are not assigned to the variable. They are initialized. In the below example, 0 is initialized into re and im. Example:
struct IntComplex {
IntComplex() : re(0), im(0) {}
int re;
int im;
};
Here, the construct : re(0), im(0)
is the initializer list.
Sometimes the term "initializer list" is also used to refer to the list of expressions in the array or struct initializer.
C++11 provides for a more powerful concept of initializer lists, by means of a template, called std::initializer_list.
Default initialization
Data initialization may occur without explicit syntax in a program to do so. For example, if static variables are declared without an initializer, then those of primitive data types are initialized with the value of zero of the corresponding type, while static objects of class type are initialized with their default constructors.
See also
- Object lifetime
- Finalizer Process & related Finalization Pattern
References
- ISBN 0-201-30983-1.