≡ Menu

Introduction to C++11 and C++14 with Example Code Snippet

Whether you’ve been using C++ for a while, or a newbie to programming, you still have to understand the basic details about C++11.

C++ programming language is based on C programming, which has been connected to UNIX from it’s beginning. Creator of C is Dennis Richie.

C++ has added many object oriented features on top of C including: classes, objects, templates, namespaces, few advanced data types, exceptions, references, STL, etc.

C++ is considered as a general purpose language that supports Object oriented programming as well as multithreading. Creator of C++ is Bjorne Strousturp.

1. What is C++11 ?

One of issues we had in C++ was the lack of standards.

The first official C++ standard started around 1998, and ever since C++ standards has been constantly improving. It was essential for its evolution to have one standard that will be official guideline for developers and organization.

This standard is officially called C++11

C++14 is just a minor extension of C++11 with few bug fixes and small changes.

This standard is registered as Information technology Programming language C++, under official name ISO/IEC 14882:2011 (widely known as C++11).

Earlier, one of the problems was when you have tried to use vector of vectors, then you might expect to write >> at the left side of definition. But you have to write > >, yes with one space in between, which didn’t make sense, and confused developer.

Now, with the adaptation of the standard, that issue is fixed. Similar to that, several small illogical syntax issues were fixed, and has become consistent.

C++ has also become compatible with previous versions of C.

We also have template aliases, several improvements to templates and algorithms, some new templates like:hash_tables, tuple and array. We have been promised metaprogramming and type trails, time utilities, inline namespaces, variadic templates.

Each and every one of these improvement could be explained in a separate detailed article. We’ll try to highlight some portion of the new standard in this article.

2. Range Based For Loop

To loop through things in a container (array, stack, list, vector, etc), we typically write a for loop like the following:

for(int i=0; i<n; ++i) doSomething;

Inside the for loop, in the first part, we initialize variable i=0; i is of int data type. You could also use unsigned init. Next we have a condition i<n. Finally, we are incrementing the i with ++i. The variable i is local for that for statement. Few times, by mistake, I tried to do something like this, which didn’t work: for(int i=0, int j=0;…

But, now, you have a for loop that could input the elements of some array, for other containers you could use: non member begin() and end().

So, if you try to intake elements into array you could use something like the following:

for(int& i: someDataStructure) { doSomething();}

If you try to present the values that are stored in array, you could protect the members of a array, and omit that & as shown below:

for(int i: someDataStructure) doSomething();

In the above two for loops, the first is using the reference, and the second enables the access by value. First way allow the modification of elements within a data structure and the second will not enable you to modify the elements in container you are using.

3. Strongly Typed enums

Old way of using enums had its flaws, which is fixed with a new way of declaring data that could have few of possible choices.

Some example situations are: months of the year, days of the week, planets in our solar system, or perhaps the lines on the four strip resistor.

Let us see how we will use this in case of coordinate system. It is known that it has four areas: first, second, third and fourth. It is bounded with coordinate lines.

For example:

enum class CoordinateArea { FirstArea, SecondArea, ThirdArea, FourthArea};

CoordinateArea caOne = CoordinateArea::FirstArea;

CoordinateArea caSome= CoordinateArea::FourhtArea;

As you might notice, you will need the scope resolution operator as well.

4. Lamba Expressions of Lambda Functions

It would be like a function that has a body but lacks the name. They are declared as shown below:

[firstPart](secondPart) TypeYouReturn{ BodyOfLambda}(acctualParameters);

firstPart is used for variable scope which will be exploited inside the lambda function. You could use more variables if have a need for that.

Keep the following in mind when you are using this syntax for the [firstPart]:

  • [] it means that you will not provide anything to give to lambda.
  • [&] it is used to say that you have some references to mess with.
  • [=] it is used to make the copy.
  • [this] is used to the enclosing class.

secondPart is necessary for parameter list for nameless function but it could be left empty as well.

TypeYouReturn is used to register what type will be returned from your lambda.

BodyOfLambda is used for actions you wish to do, in here you will type some code that will be used to perform actions you are intended to apply in the body of this function.

actualParameters are used to provide input into lambda function.

An example of lambda function:

double dUpperPart = [](double dX, double dY)double{ return dX*dX +dY*dY;} 

Another example of lambada function:

vectror<int> iVector;
for_each( begin(iVector), end(iVector), [](int n){if(n%2==0)cout<<n<<end;});

5. Static Assertion

In your code, if you try to input the value that is out of range or the value that should not been imputed, it is a good candidate for static assertion.

This has two parts:

  • First, the expression that gets evaluated
  • Second, the string literal that is presented as a message if test condition is not matched.

Here is the syntax:

static_assert(evaluatedExpression, stringMessage);

An example usage for static_assert:

static_assert(sizeof(long long int)>=16;”This is unexpected”);

6. Random Number Generation

This has been around for a very long time. The old way of generating random numbers was replaced with a new approach.

To see how it is done just visit Bjorne’s site, there is good example on how to deal with random numbers.

7. Move and &&

For this, we need to understand lvalue and rvalue.

l stands for left side. It is one of the basic properties lvalue has it is an object in memory that could be at the left side of expression; an example would be some variable.

r stands for right side. This will be located on the right side of expression and it should not be found on right side, the specimen for it is a constant.

In older standard we could use only lvalues as reference, now that has changed and you could use rvalue as reference as well. It is useful in situations where you need to copy some objects, the better solution for that is using the move semantics.

To apply the move constructor in class you would call it like this:

MovableClass(MovableClass&&);

And, if you need move assignment it is called like this:

MovableClass&& operator=(MovableClass&&); 

In the new standard, this is well supported and containers and algorithms use this move semantics with appropriate optimizations.

8. Few Notes about Pointers

Pointers is one of the important concepts in C++ and C.

As you already know, they are used to store the address of some object in memory and that way you have a lot of flexibility for your code.

The dynamic data structures could be constructed, you have very fast way to access the elements of an array, etc.

There are few things that are worth mentioning about pointers.

First, is the replacement of NULL with nullptr. This means that your pointer is not holding an address but it has nothing to point to. It is something like you have variable that has zero value, but it is has some differences as well.

The next few things are new types of smart pointers: unique, shared and weak pointers. Let us discuss what are they used for.

unique_ptr is new feature of C++ that will enable you to protect ownership of some resource stored in the memory. If something has ownership it could not be shared, but it is movable. This means that you could transfer it to another unique pointer.

shared_ptr as one could guess from the name is suitable for situations that require ownership of some resource in the memory to be shared.

weak_ptr is enabling the access to something that might exist in memory, the access is granted if you have object that occupy the memory, and it is possible to delete that object, the necessary destructor is called upon if it has been used last time.

The example for unique_ptr, will resolve exception unsafe code.

The syntax for unique pointer:

unique_ptr<someType> suniquePtr(new someType(args));
...
uniquePtr.release();

For shared_ptr, declaration would be like this:

shared_ptr<someType> somePtr(new someType(args));

Weak pointer syntax:

weak_ptr<someType> weakPtr= somePtr;

9. Uniform Initialization and Initializer Lists

If you wish to use constructor it would be preferable to replace old style initialization () with couple of {}.

Old style of initialization with constructor could be implemented like this:

CSomeClass SomeObject( argument1, argument2);

The above would be changed to something like this:

CSomeClass SomeObject={ argument1, argument2};

If you are in situation to put some values into vectors it was usual to use push_back few times, or it was achievable with initialization that used old style brackets, which are obsolete now days,

vector <int> ourVector;
for(int i=0; i<5; ourVector.push_back(i++));

It is better to do it as shown below. In the following, you will still be able to add elements to end of the list, but now it is more uniform from syntax point of view:

vector< int> ourVector={0,1,2,3,4,};

Improvements to Constructor

If you try to calculate sum, minimum, or count how many numbers are fulfilling some condition, you could initialize the variable with some value.

So, if you try to find analogy with classes and data types, you would ask you self could you initialize some member of a class with value 0.

It is possible to do such a thing if your compiler supports new standard.

The usual way to do this would be:

class CSomeClass
{
private:
	int nSomeValue=0;
...
}

This way if you call the constructor it will put those values into nSomeValue, but if you omit to write your own constructor value 0 will be stored as some starting value into place that is being reserved by that nSomeValue. It is useful and I would recommend you to us it.

Next thing that you might like is delegating the constructor. It means that once you write one constructor it becomes reusable in other constructors as well.

One interesting thing we have is inherited constructor to. Now if you could use constructor if you need it in CChild class.

To do that you would write something like this:

class CChild: public CParent
{
public:
using CParent::CParent  
}

10. Challenges with Virtual Function

If you are familiar with virtual methods you would know that it is important to have them because pointer should “know” which of the methods to access.

When there is inheritance and you need to apply virtual methods, it is enough to write virtual in the front of the name and every time you have method in lower level class you will dill with a virtual method.

There are few other problems as well, one of them is large table that is used to keep the track of the methods and it could become bit slow speed vise, but I will not spend too much time on them, I would prefer to present you a solution for some of those problems, and override and final are magical solutions for now.

If you try to override the function, this could mean that you wish to work with data type that is different form that one applied in parent class, but you are in need to change how method in inherited class behaves, now all you need to do is to add override and you are not overloading the method, but overriding it.

To apply that, you just add override and what you desire is done.

In the case that you wish to prevent the method to be over written, you add final in the front of the method, and then it will be impossible to modify how method is acting.

11. Multi-Threading in C++11

For a long time we did not have some standards to use more threads in your program.

Different companies have noticed that programmers need something like that, so they have developed their own libraries for that. The most popular is POSIX.

The following are few things to keep in mind when you write threads:

  • If you wish to call the thread, which is a class in std namespace, you need to add some header. The appropriate is to add include <thread>, or it might signed some other way.
  • When you start your thread you could use: join, swap, detach, sleep for etc.
  • If you try to protect some resource from other threads so that you have expected results now you should have different kinds of mutex that is added with its library: mutex, recursive mutex, timed mutex and recursive timed mutex.

12. Example Code for C++11 Style

Now, we will look at few examples that will illustrate the new style of C++11. Keep in mind that your compiler should support this.

First example for C++11 standard:

#include <iostream>

using namespace std;

int 
main(void)
{
int ourArray[5];

for(int& i: ourArray)
{
cout<<”Next element is->”;
cin>>i;
}

cout<<”Elements  in array are!”<<endl;
for(int i: ourArray)  cout<<n<<endl;

return 0;
}

Second example for C++ standard with vectors:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int
main(void)
{
vectro<int> nVector { 0, 5, -3, 11, -3, 7, 0, 2, 7, -6, 11, 0, 21, 12, -5};

for_each(nVector.begin();
                nVectro.end();
 [](int i)
{
    cout<<n<<” is”
    if(n==0)
       cout<<” zero ”;
   else if(n>0)
       cout<<” positive “;
   else 
       cout<<” negative “
   cout<<”number\n”;
}           );

return 0;
}

You could try to use few examples with array as a new container like: tuple or some other.

To use tuple you could do it like this:

auto tuple = make_tuple(“triangle”, ‘t’, 10, 15, 20);

To declare map that will have one element string and another is vector you could do it like this:

map<string,vector<int>> aMap;

13. What is Next for C++11

There are several minor improvements and bug fixes to C++11 standard, which is known as C++14.

So what should we at least hope for: genetic lambdas, lambda capture expressions, function return type deduction, variable templates, binary literals and few standard library features as well.

Currently C++17 standards is under development, which is expected to be released by end of 2017.

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Aridzonan_13 February 4, 2016, 11:41 am

    Is there a gcc ver. or other Linux based compiler that supports =>C++11?

  • Jason Moore March 12, 2016, 11:31 am

    I just saw this and enjoyed it. It was very informative, thanks. I am a beginning/intermediate user of c++ and linux. I have always enjoyed your site and emails. Keep up the good work.

  • DuskoKoscica March 22, 2016, 11:18 am

    Well, for that you have many sites.
    Now, you even have on line site that has C++ with C++11. There is way more stuff out there.
    For me this will do it
    http://www.universetoday.com/127916/penumbral-lunar-eclipse/

    don’t forget sites that could be found with google, yahoo, bing, yandex, ask jews….

  • DuskoKoscica April 6, 2016, 6:18 am

    This moon looks interesting
    http://www.cnet.com/news/sorry-the-moon-wont-turn-green-on-april-20/

    Now it is green.

  • Kranti February 28, 2017, 12:35 am

    Nice Article with introduction about C++11 articulated in a very understandable way…