1. const fields - Intialization List #
Created Saturday 11 January 2020
-
How do we work with const data members? If we don’t initialize, then the value is stuck and will be the same for all objects.
-
C++ does not allow initialization outside a function.
To solve this problem, we need to use initialization lists.
Syntax
class A{
int a, b;
const string c;
int d[4];
...
void f() : a(2), b(a), c("Sanjar"), d{1,2,3,4} // intialization list
{
...
}
...
};
- We can initialize any data member using i-lists
- It is the first thing that is run, when an object is being created.
- Variables in the i-list are not initialized in the order that they are specified in the i-list. Instead, they are initialized in the order in which they are declared in the class.
- Making a constructor(with initialization list) is a must if at least one data member is const or reference.
- We should not write ‘this’ in the initialization list, except for a reference variable. That would give an error. The names are not overshadowed here.
Use case:
- If we want a const data member.
- If our class has reference data members. (Both need to be declarized).
- In C++11 and higher, we can initialize const and references just outside the constructor too.
- Even here, the initialization list is evaluated first.