The c++ 11 standard is a new c++ programming language standard. c++ 11 is new extension of old c++ 03 standard. In this blog post we would learn c++ 11 standard with example code. Kindly do practice with each example.

introduction to c++ 11 standard with examples (tutorial 1)

image credit http://www.liveboxcloud.com/c11-and-the-nullptr-keyword/

introduction to c++ 11 standard with examples (tutorial 1)

c++ 11 initializer lists

Every c++ programmer is familiar with this concept. For example we initialize array like int arr[5] = {1,3,5,7,8}. Here {1,3,5,7,8} is our initializer lists. The expression int arr[5] = {1,3,5,7,8} works in both c++ 03 and c++ 11,however if we have an stl vector (vector<int> foo) , then only way we can initialize the vector foo is as follows

foo.push_back(1);
foo.push_back(3);
foo.push_back(5);
foo.push_back(7);
foo.push_back(8);

c++ 11 extends the initializer lists support to the all stl containers. so we can initialize the foo vector as vector<int> foo = {1,3,5,7,8}.

#include<iostream>
#include<vector>
using namespace std;

vector<int> foo = {1,3,5,7,8}; //calls initializer_list constructor

int main()
{
  return 0;
}

Uniform Initialization c++ 11 and c++ 14

Uniform Initialization expands on the Initializer List syntax. In c++ 03 standard , it allows aggregate initialization of c++ class. let us see below example.

#include<iostream>
using namespace std;

class foo
{
public:
	int salary;
	string employee_name;
};

int main()
{
	foo foo_obj={20000,"Mr. Lee"};// aggregate initialization
	return 0;
}

In c++ 11 standard , it allows aggregate initialization and initialization with initializer list. let us see below example.

#include<iostream>
#include<initializer_list>
#include<vector>
using namespace std;

class foo {
public:
	int salary;
	foo(int salary_) { // aggregate initialization
		cout << "in foo(int salary_) constructor\n";
		salary = salary_;
	}
	foo(const initializer_list<int> vec) { // initialize_list initialization
		cout << " In foo(const initializer_list<int> vec) constructor\n";
		salary = *(vec.begin());
	}
};

int main() {
	foo foo_obj = { 20000 };
	return 0;
}

Let us compile the above code:  g++ -std=c++11 main.cpp

When we run the program it will give output:

 In  foo(const initializer_list<int> vec) constructor

The output tells that in uniform initialization searches the initializer list constructor first. so in case of uniform initialization the search priority would be

  • initializer_list constructor.
  • Regular constructor taking parameters.
  • Aggregate constructor.

Read our next tutorial 2 about c++ 11 nullptr, auto and range based for loop >>

Ref:

https://en.wikipedia.org/wiki/C%2B%2B11

https://isocpp.org/wiki/faq/cpp11



Related Contents to follow