Learning New C++ Standards - Uniform initialization

| | 1 min read

Older versions of C++ has different ways to initialize types. But with new C++ standards defined a uniform way to initialize any type of objects. Use braces ({})for initializing types.


  class CObject
  {
	  int i;
	  public:
	  CObject(int k):i(k){}
  };

To initialize this type use following syntax.

  CObject myObj{3};
  CObject myObj = {3};
  int j{10};

If there is no constructor and the data member is public then also this initialization can initialize the aggregate object. Containers are initialized with this.


vector <int>  vec {1,2,3,4};

This will initialize vector vec with 4 elements of value 1,2,3,4.