Skip to main content

Posts

Showing posts with the label Cpp 14

C++ 17 Introduction

C++17 has brought a lot of features to the C++ language. Let’s dig into three of them that help make coding easier, more concise, intuitive and correct. We’ll begin with Structured Bindings. These were introduced as a means to allow a single definition to define multiple variables with different types. Structured bindings apply to many situations, and we’ll see several cases where they can make code more concise and simpler. Then we’ll see Template Argument Deduction, which allows us to remove template arguments that we’re used to typing, but that we really shouldn’t need to. And we’ll finish with Selection Initialization, which gives us more control about object scoping and lets us define values where they belong.

Initializer list in C++

C++ 11 Initializer : // C++ 03 class Dog {     // Aggregate class or struct    public:       int age;       string name; }; Dog d1 = {5, "Henry"};   // Aggregate Initialization // C++ 11 Initializer extended the scope of curly brace initialization. class Dog  {    public:       Dog(int age, string name) {...}; }; Dog d1 = {5, "Henry"};  /* Uniform Initialization Search Order:  * 1. Initializer_list constructor  * 2. Regular constructor that takes the appropriate parameters.  * 3. Aggregate initializer.  */ Dog d1{3}; class Dog  {    public:    int age;                                // 3rd choice    Dog(int a)     {                            /...

Auto keyword | C++ 11 | C++ 14

The auto keyword was a way to explicitly specify that a variable should have automatic duration: int main() {     auto int foo(5); // explicitly specify that foo should have automatic duration     return 0; } Auto in C++  11:  In C++11, the meaning of the auto keyword has changed, consider the following statement: double d = 5.0; Starting with C++11, When initializing a variable, the auto keyword can be used in place of the variable type to tell the compiler to infer the variable’s type from the initializer’s type. This is called type inference (also sometimes called type deduction). For example: auto d = 5.0; // 5.0 is a double literal, so d will be type double auto i = 1 + 2; // 1 + 2 evaluates to an integer, so i will be type int This even works with the return values from functions: int add(int x, int y) {     return x + y; } int main() {     auto sum = add(5, 6); // add() returns an int, so sum ...