Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

Uniform Initialization


Contents

Before C++ there were different approaches to initializatio of variables, arrays and objects. C++ 11 introduces a braces notation for initialization.

File: ui1.cpp
#include <iostream>
#include <map>

using namespace std ;

class A1
{
  public:

  A1( )
   {
             cout << "Default constructor." << endl ;
   }

  A1( int i1 )
   {
   }

  A1( const A1& a1Object )
   {
       cout << "Copy constructor." << endl ;
   }


};


class A2
{
    int arr[3];

}

int main()
{
  int i1 ;
  //uninitialized variable

  int i2{} ;
  //Using Braces

  int j1(10) ;
  //initialized variable

  int j2{ 10 } ;
  //Using Braces

  int arr1[] = {1, 2, 3, 4}   ;
  // Aggregate initialization

  int arr2[]{1, 2, 3, 4} ;
  //Using Braces


  A1 a1Object ;
  //Default Constructor

  A1 a2Object{} ;
  // Using Braces

  A1 b1Object( 3)  ;
  //Parametrized Constructor

  A1 b1aObject = 3  ;
  //Parametrized Constructor

  A1 b2Object{3} ;
  // Using Braces

  A1 c1Object = a1Object  ;
  //Copy Constructor

  A1 c2Object{a1Object} ;
  // Using Braces


   // declaring a dynamic array
   // and initializing using braces
   int* p1 = new int[5]{ 1, 2, 3, 4, 5 };


  return 0 ;
}
We can also use the braces to initialize an array declared in a class.

File: ui2.cpp
#include <iostream>
#include <map>

using namespace std ;

class A1
{
  public:

    int arr1[3] = {1, 2, 3};


  A1( ) : arr1{1, 2, 3, 4, 5}
   {
             cout << "Default constructor." << endl ;
   }

  A1( int i1 )
   {
   }

  A1( const A1& a1Object )
   {
       cout << "Copy constructor." << endl ;
   }


};



int main()
{



  return 0 ;
}