C++11 Features

auto, range-for, nullptr, lambdas

Interview Relevant: Modern C++ foundation

C++11 Features

C++11 (Modern C++) introduced a massive set of features that fundamentally changed how C++ is written.

Key Features

  • Type Inference (auto): Let the compiler deduce types.
  • Range-based for loops: Cleaner iteration over containers.
  • Smart Pointers: unique_ptr and shared_ptr for automatic memory management.
  • Move Semantics: Efficient resource transfer using rvalue references (&&).
  • Lambdas: Anonymous functions for callbacks and algorithms.
  • nullptr: Type-safe null pointer constant.

Code Examples

Key C++11 features that modernized the language.

cpp
1// auto type inference
2auto x = 42;
3auto vec = vector<int>{1, 2, 3};
4
5// Range-based for
6for (const auto& item : vec) {
7    cout << item << endl;
8}
9
10// nullptr (replaces NULL)
11int* ptr = nullptr;
12
13// Lambdas
14auto add = [](int a, int b) { return a + b; };
15
16// Move semantics
17string s1 = "hello";
18string s2 = move(s1);  // s1 is now empty
19
20// Smart pointers
21auto p = make_unique<int>(42);
22auto sp = make_shared<int>(42);
23
24// Uniform initialization
25vector<int> v{1, 2, 3};
26int arr[]{1, 2, 3};
27
28// constexpr
29constexpr int square(int x) { return x * x; }
30
31// decltype
32decltype(x) y = 10;  // y is int
33
34// Rvalue references
35void process(int&& val) { }
36
37// Variadic templates
38template<typename... Args> void print(Args... args);
39
40// Initializer lists
41vector<int> v = {1, 2, 3, 4, 5};

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In