In C++, initialization or initializers are expressions that set the initial state of variables or objects, often appearing in contexts such as object creation, member initialization, array assignment, etc.
Direct Initialization#
Direct initialization can use ()
or {}
to initialize variables:
int a(10);
int b{10};
// Member initialization expression list is a form of direct initialization
MyClass(int a, int b): x(a), y(b){
// do something..
}
Direct initialization can invoke explicit constructors.
Copy Initialization#
Copy initialization uses the assignment operator =
, unlike direct initialization, it cannot invoke explicit constructors.
int a = 10;
shared_ptr<int> p = new int(10); // Error
List Initialization#
List initialization is a new feature introduced after C++11, allowing the use of braces {}
to initialize variables of any type, preventing narrowing conversions (implicit conversion from one type to another causing loss of precision, etc.: int x{4.2}).
MyClass myClass = {1,2,3};
// or
MyClass myClass = new MyClass{1,2,3};
std::vector<int> v = {1,2,3};
Aggregate (struct) Initialization#
An aggregate is a class or struct that has no user-defined constructors, no private or protected non-static data members, no base classes, and no virtual functions.
For aggregate types, braces can be used to initialize their members, for example:
struct Point {int x; int y;};
Point p = {1, 2};
Default Member Initializer#
Default member initializer is a new feature introduced in C++11, allowing direct specification of default values for member variables in class definitions.
class MyClass{
int x = 4;
int y = 2;
public:
MyClass() = default; // Initialize using default constructor and default member initializer
// do something ..
}