Skip to main content

Posts

Showing posts from 2013

Boost - shared pointer

Shared pointer is another kind of Boost library's pointer. It is similar to scoped pointer but shared pointer allows share ownership of object. We are able to assign two or more pointers pointing to the same object (it was impossible for scoped pointer). Take a look to the example below: Output of this example is: In point I we are initializing two shared pointers pointing to two separate instances of TestClass class, then we are printing its values in point II. Point III shows use difference between shared pointer and scoped pointer. We are assigning two pointers to the same object of class TestClass . In this point object having testValue==5 is being destroyed (because we remove the only one pointer to that object). Also, we have two pointers pointing to objects having testValue==6 now. Note that that object will be destroyed when last shared pointer pointing to them will be destroyed ( int our case it is destroyed when we are reaching end of main() function)

C++11 - Lambda functions

C++11 standard introduces new type of functions for C++ programming - lambda functions. Lambda function is a anonymous (unnamed) function which you can write directly inline in the code. Lambda function allows do some operations visible like a function without declaring it as a function (saving space and time). C++ lambda function has following syntax: [capture](arguments){body} capture - value which should be captured outside of body class arguments - list of arguments of function (the same syntax as for normal C++ functions) body - body of function - statements which should be exectued when function is invoked For better understanding take a look fo below example: Output of this example is: In point I we are initializing vector using C++11 initializer_list Point II is key point of our example. It demonstrate using lambda function (3rd argument of for_each function) together with with for_each algorithm of STL library in order to calculate sum of vector element

C++14 - Tuple addressing via type

Today I would like to introduce one of new features which will arrive to C++ with new language standard (C++14) which is going to be release in 2014. In order to compile example from this article you need to have compiler supporting C++14 standard. The newest version of GCC supports it. I would like to introduce you features called Tuple addressing via type which allows us to get tuple element value using type name instead of tuple parameter number. Of course it is possible only for type names which are not ambiguous. Let's take a look on below example for better understanding: In point I we are declaring our tuple type containng of 2 int elements and on string element. In point II we are using std::get function to get values of our tuple typed variable using tuple parameters numbers. This feature is well known from C++11 standard. Point III shows new (introduced in C++14 standard) way of getting values of tuple elements. We are getting string type element using

Interview with Bjarne Stroustrup - father of C++

Today I would like to recommend you very interesting interview with Bjarne Stroustrup - the inventor of C++ programming language. You can find out what Bjarne thing about increasing growing of impact of web technologies and languages with comparison to C++ applications. Bjarne also give an advices about technologies which young programmers should learn to be better developers. You will also be able to find out why Bjarne think that software development can be noble profession in the future. All those information and many more you can find here: Interview with Bjarne Stroustrup Enjoy!

STL - count and count_if algorithms

One of the basic and most useful STL algorithms is algorithm which can be used to count number of elements within selected container according to specified criteria. In order to do that we can use std::count or std::count_if algorithm. std::count (firstElementIterator, lastElementIterator, elementForSearch) - is function which will go through container using firstElementIterator and lastElementIterator and return number of container elements which value is equal elementForSearch std::count_if (firstElementIterator, lastElementIterator, UnaryPredicateFunction) - is function which examine range from firstElementIterator to lastElementIterator and return number of container elements which fulfill UnaryPredicateFunction criteria. UnaryPredicateFunction is function having following signature: bool functionName(const Type& a) . So, count_if returns number of elements where UnaryPredicateFunction returns true for. For better understanding let's take a

STL - iterators mechanism

Iterators are a generalization of pointers which allow a programmer to work with different data structures in the uniform manner .  In STL we are using iterators to go through STL container for getting and setting values of its elements. In order to better understand working with iterators, take a look on below example: Output of this example is: In point I we are defining two vector containers using C++11 initializer lists . Point II shows as definition of iterator which we will use to go through our vector structures to examine their elements. We are setting our iterator to first element of our myVector container. Because iterators are generalized pointers we can imagine this operation as setting up pointer to the first element of our structure. This operation can be illustrated like Step 1 on the picture below. In C++11 we can simplify declaration of STL iterators using auto type as shown in point IIa. In point III, IV and V we can see process of going through con

QT - Signal-slot mechanism

This is first article describing some aspects of programming with Qt framework. I am going to focus on most important basic feature of Qt framework: signal-slot mechanism . At the beginning take a look on below QT code: Output of that code is this window: This quick code is something like "Hello world" of Qt programming. Let's take a detailed look on the code. In point I we are declaring QApplication object which will contain indefinite loop which will be invoked after program starts in order to wait for user interactions. We can also analyse command line input parameters in this line, but we are not doing it because we do not have any input parameters for our application. In point II we are declaring QPushButton object which will be the only object of our application. As only parameter of our definition we are putting text which should be displayed on our button - "Hello World" . Point III is key point of this example. It presents basic

STL - Map keys difference

Today, I would like to show how to quickly find difference between two maps of STL library basing on keys only. We need to compare two maps of STL library and find third map which will contain only those elements of first map which keys are not being placed within second map. Take a look on code: Output of this code is: In point I we are defining struct type having overloaded of operator() . This structure will be used as function object to compare two elements of maps ( std::pair ) basing on keys only. In point II we are defining two maps which will be compared. We are going to receive all std::pair s from firstMap which keys are not being placed within  secondMap . In point II we are declaring diffMap map which will contain result of our differentiation. Point IV is key point of our function. In that point we are using std::set_difference algorithm. This algorithm returns difference of two ranges of STL containers. First 4 arguments are begins and ends of two ranges o

lvalue - definition

Today I found very interesting definition of lvalue  in C++. According to this site: An lvalue is an expression that refers to a memory location and allows us to take the address of that memory location via the  &  operator. An rvalue is an expression that is not an lvalue.  Examples are: // lvalues: // int i = 42; i = 43; // ok, i is an lvalue int* p = &i; // ok, i is an lvalue int& foo(); foo() = 42; // ok, foo() is an lvalue int* p1 = &foo(); // ok, foo() is an lvalue // rvalues: // int foobar(); int j = 0; j = foobar(); // ok, foobar() is an rvalue int* p2 = &foobar(); // error, cannot take the address of an rvalue j = 42; // ok, 42 is an rvalue

Boost - Scoped pointer

Here is the first article about Boost libraries features. I am starting that new series of articles with explanation of scoped_ptr - one of the Boost smart pointers . scoped_ptr is smart pointer that is the only owner of dynamically allocated object and is automatically freed allocated memory when destructor of scoped_ptr is called. See example below: Output of this example is: In point I and II we are defining two scoped_ptr pointers - one for int and one for Test (custom class) object. Notice comment marked as Ia. That is impossible operation for scoped_ptr . It is trying to assign ownership of allocated object to second pointer. scoped_ptr does not allow it. It have to be sole owner of its object. Point III shows how we can assign new values to object which refers to scoped_ptr . We can use dereference operator ( operator* ) as for normal pointers (this operator is overloaded in Boost smart pointers) as well as use get() function implemented to Boost smart po

Advanced C++ - Template classes

Template class concept is similar to template functions . It allows creating generic type classes, which means that we can have many different classes which differ only in terms of types using one class code only. See example below for better explanation: Output of this example is: Point I depicts definition of template class. As you can see it is very similar to definition of template function. We are defining myType as type which will be replaced with real type during usage of template class. Then we are defining class normally with usage of mapped temporary type. Points II and III shows how to use template class for different class. We are defining two instances of our template class - for int and double types. Compiler will implicitely generate bodies of two clases based on those types and template definition. As for template functions, we are selecting real type using angle brackets. Above example you can find on our github repository here: https://github.com/xmeme

Advanced C++ - Template Functions

Template function are special types of C++ function which can be used with different types (generic types). Thanks to that we can create one body of function which can be used for many different types. When we are creating template function compiler does not define any function for use at that time. Generation of funciton basing on templates are done during compilation process basing of differnt usage of template class. For better understanding take a look on following example: Output of this example is: In point I, we are defining template function which should return sum of two parameters. Without templates we need to define such function separately for each type which we should use it with (ex. separate function for int type, separate for double , separate for any other type). Thanks to template we can generate body of that function only once (as in point I) and use it to any type which is able to use body of that function. In our example we can use this template for an

C++ Software Debugging - basics

I met very interesting article about basic rules of software debugging. Article is shared from University of Cambridge. I think, everyone should get know with that article. You can find it here: C++ Basics of Software Debugging - University of Cambridge

C++14 - Info graphic

Today I found interesting info graphic which depicts news which are being planned in new C++ standard which should be released in next year (C++14). You can see the info graphic below Source:  http://isocpp.org/files/img/wg21-timeline.png

Advanced C++ - Conversion constructor and operator

When we are defining class we sometimes would like to allow easily convert that class from and to previously defined-type objects (ex. int ). We can do that using conversion constructor and conversion operator: conversion constructor - it is constructor which has one parameter - type which constructor should allow to convert from. It allows to convert previously defined object of type as in constructor paramter into object of class where constructor belongs to conversion operator - it is overloaded operator type() - where type is type of object which we can convert this class object into Let's see below example for better understanding: Output of this example is: In that example in our class TestClass we are defining two conversion constructors. conversion constructor for type int (point I) conversion constructor for type string (point II) Next in main function we are invoking that constructors converting int and string types to our class TestClass type (p

Advanced C++ - Compiler generated functions

When we define some class in our C++ code, compiler is generating some important functions for our class (unless we define it explicitly). Those functions (sometimes called Compiled Generated Functions ) are:  default constructor   destructor   copy constructor   copy assignment operator  During compilation, compiler knows our code and classes usage, so when we are using one of above functions implicitly, it generate that function implicitly for us in the class body. For better explenation, let's see the example below: In point (I) we are defining class TestClass . This class seems to be empty. However we are implicitly using following function in main class:  point III - we are implicitly using defualt constructor in order to create instance of TestClass - default constructor of TestClass is implicitly generated by compiler   point IV - we are using copy constructor of TestClass in order to copy instance to instance2 - copy constructor of TestClass is im

Github Gist code snippets

From today I will use GitHub Gists mechanism to insert code snippets to this blog. Example GitHub Gist for C++ Hello World snippet you can see below. I hope this change make blog readability better. In the free time, I will also try to update previous' posts code snippets using GitHub Gist. UPDATE: Previous' posts code snippets updated to GitHub Gists. Enjoy!

C++11 - Right angle bracket

In C++03 " >> " is always interpreted as right shift operator . It causes problem for nested template declaration like here: In above example for C++03 we have compilation error because of unintended interpretation of " >> ". Compiler interpret it as right shift operator - not like two nested vectors. Proper syntax in above situation should include space character between two " > " characters closing nested templates like here: It it not very comfortable and sometimes causes problems with finding reason of compilation error. Fortunately, C++11 standard solves that problem. It implements proper interpretation of nested templates without space between two right angle operators " > ". Therfore in C++11 following syntax: is properly interprated as two nested vectors.

Advanced C++ - Function object

Function object is object which has function-call operator ( operator() ) defined or overloaded. Thanks to that objects have behaviour of function which means that you can call such object by using paranthenses and passing arguments. Let's see and example: The output of this example is: In point (II) we are defining function object according to class defined in point (I). In point (III) we are using our function object like a normal function.  You may be considering what is advantage of usage function object instead of normal function. Here are few advantages of function object:   1. Function object can be used as normal function but can has also additional abilities related to being object ex. the same function, represente by different function object, can has different states at the same time.   2. Function object has own types. What is more different function objects can has different states even if they signature is the same. This is very useful in STL library. Than

STL - sort() and is_sorted() algorithms

Today I would like to show first article about some example of usage STL ( Standard Template Library ) library and its algorithms. First thing which I would like to present is usage of std::sort() and std::is_sorted() algorithms. Function std::sort() sorts selected range of elements of container in ascending order. Function std::is_sorted() checks whether selected range of elements of container is sorted in ascending order. Take a look at following example of usage those functions: Output of below example is: At the beginning of that example we declare vector of int-typed elements using initializer_list  and prints it using range-based for loop (URL). In point (I) we are using std::is_sorted () function to check whether vector is sorted according to ascending order. Notice that we are iterating through whole vector (from testVector.begin() to testVector.end() ). Function returns false because our vector is not sorted yet. We can see results in first line of output. In

C++11 - Explicit override and final

Consider following inheritance situation: Question is: will we have two override_func() functions in derived1 or only one because override_func(double a) from derived1 overrides override_func(int a) from base_class? Two, of course. It is because those functions has different signature (different types of arguments in this case). However sometimes user does not notice it and think that function override_func(double a) overrides function override_func(double a) in derived1 class. It can cause problem especially if someone is doing some modifications in override_func(int a) in base class and expects that those changes will have inpact on override_func(double a) from derived1 class. C++11 has smart mechanism which allow to notify compiler and other users that in derived class we would like to override function having exact the same signature in base class. It can be done using override keyword. Let's declare override_func(double a) in derived1 class this way: What happend's her

Advanced C++ - Anonymous namespaces

Anonymous namespace is kind of namespace with no specified name. Such kind of namespace is visible only within file where it is defined within. I allows define variables and functions which could be visible as global, but within one file only. Thanks to that such files are not global within whole program. It also allow avoids making global static variable. Let's see an example of defining and usage of anonymous namespace. Consider following main.cpp file: In the above example we have anonymous namespace containing one int typed variable. This variable can be used as global variable withing this main.cpp file but will not be visible inside any other files. That is simple example of usage anonymous variables. If you would like to compile it and play with it (changing or adding some parts of code to check what happends than) you can download it from here:  https://github.com/xmementoit/CppAdventureExamples/tree/master/advancedCpp/anonymousNamespace

C++11 - Tuple type

In C++11 tuple type is collection of heterogeneous (different types) elements of pre-arranged dimensions. tuple is similar to fixed sized vector but the difference is that it can store elements of different types (while vector can store different of only one type). Let’s see some simple definition of tuple type: We defined tuple class having fix size. Size of this tuple is sizeof(string) + sizeof(double) + sizeof(int) . Variable of our test_tuple type will be able to store three variables of different types ( string, double, int ) and can be initialized like here: In order to get value of concrete position of tuple we can use std::get template in the following way: This instruction will get value of 2nd parametr of myTupleObject variable of tuple type (remember - numering from 0 as usual in C++) and assign that value to test_int variable. In order to set (overwrite) value of concrete position of tuple object need ot use std::get template too: You can to do it this w

C++11 - Initializer lists

In previous version of C++ standard (C++03) we was able to do following array elements assignment: But we have not been able to do similar assignments to vector : In order to assign above three elements to vector we had to invoke push_back () method three times: C++11 present feature which help with above inconvenience. This feature can be achieved thanks to initializer_list template. In C++11, vector implementation has assignment operator taking initializer_list template as parameter: Thanks to that we can use following assignments to vector : The same way we can overload assignement operator of any of own class, as well as constructor or any function. Such definition can can take initializer_list template as parameter. Then we will be able to pass initialization list having syntax: { element1, element2, element3,...} as parameter of such function. Of course STL vector container has implemented constructor having initializer_list as parameter, too. So you can also

C++11 - Range-based for loops

Another interesting new feature of C++11 standard is range-based for loop. This feature is simplification of usage of for loop going through each element of some container (ex. vector ). For other programming languages we can use following syntax when we would like to iterate through all container elements: Those constructions are very simple and rather self-understandable. However in C++ until now (C++03 standard) we had to use following syntax when we would like to go through each element of container: Complicated, right? Especially for beginner user who is just starting learning of C++ and STL library. So, how to simplity it? C++11 helps us here :) It defines new syntax for dealing with 'for each' iteration called "range-based for loop". Instead of above vector iteration we can do something like this: Definitely simpler, more understandable and easier to read, I think. What is more when we do not know exact type of data in our container we can use auto

C++11 - Auto type

At the beginning I would like to explain you one small new feature of C++11 standard. This feature is auto type. auto is new C++11 type keyword which automatically deducts type of variable. See example below: What is type of variable b ?  int of course. C++11 can automatically deduct type of variables using auto type. However remember - there is not desirable to use auto too often. It can make your code less readable. Try to use defined types as often as possible. Nevertheless, there is little more useful example of usage auto type. Let say that we have been declared following map containing two strings as key-value instances: Now if we would like to iterate through elements of above map in previous version of C++ (C++03) we had to declare iterator following way for example: Thanks to auto type C++11 allow us to declare it that way: Shorter and more comfortable. That's it for the beginning. I hope you understand usage auto type in C++11 right now. Write your pro

Welcome C++ lovers

Welcome all C++ lovers. I am starting this blog to share my C++ adventure with you. I will try to explain here usage of some C++ features as well as I will describe my experience with working as C++ developer. I hope you will find a lot of useful informations here. All comments are welcome. Let's start our common C++ adventure. Hello world :)