- Examples
Examples for using {} for uniform initialization and initializer lists.
We'll cover the following...
Example 1
Press + to interact
// uniformInitialization.cpp#include <map>#include <vector>#include <string>// Initialization of a C-Array as attribute of a classclass Array{public:Array(): myData{1,2,3,4,5}{}private:int myData[5];};class MyClass{public:int x;double y;};class MyClass2{public:MyClass2(int fir, double sec):x{fir},y{sec} {};private:int x;double y;};int main(){// Direct Initialization of a standard containerint intArray[] = {1,2,3,4,5};std::vector<int> intArray1{1,2,3,4,5};std::map<std::string,int> myMap{{"Scott",1976}, {"Dijkstra",1972}};// Initialization of a const heap arrayconst float* pData= new const float[3]{1.1,2.2,3.3};Array arr;// Defaut Initialization of a arbitrary objectint i{}; // i becomes 0std::string s{}; // s becomes ""std::vector<float> v{}; // v becomes an empty vectordouble d{}; // d becomes 0.0// Initializations of an arbitrary object using public attributesMyClass myClass{2011,3.14};MyClass myClass1 = {2011,3.14};// Initializations of an arbitrary object using the constructorMyClass2 myClass2{2011,3.14};MyClass2 myClass3 = {2011,3.14};}
Explanation
-
Firstly, the direct initialization of the
C array
, thestd::vector
, and thestd::map
(lines 32 - 34) is quite easy. In the case of thestd::map
, the inner{}
-pairs are the key and value pairs. -
The next special use case is the direct initialization of a const
C array
on the heap (line 36). The special thing about the arrayarr
in line 39 ...