Tutorial [Tutorial] How to start programming in C++ (Part 4)

Discussion in 'Develop Coding Skills - Tutorials' started by JM Security, Mar 11, 2016.

  1. JM Security

    JM Security Level 28

    Apr 12, 2015
    SecureMyBit Developer
    Hi all!

    Previous article here: [Tutorial] How to start programming in C++ (Part 3)

    The cast

    When you declare variables of different types you need to be careful that you do not tangled within the same algebraic expression, or assignment, values and/or variables of different types. The compiler reports generic type mismatch error (type mismatch) when you try to force a value of a type to a variable declared to be of type incompatible with that value. In some cases the compiler makes a stretch, for example, if you try to add a float value in a variable of type int: clearly the portion is truncated.

    Sometimes, however, may affect make changes on the fly to keep the results of certain operations on variables of different types, primarily when you go from a smaller to a larger type. In such cases the C++ language programmer provides a construct called cast.

    This program despite expectations (dictated by the fact that the variable three declared float) will produce a null result. The Division is made out of two values of type int, the result is stored temporarily in a variable of type int, and only at the end, kept in a float variable. It is clear at this point that the three variable will only contain the integer part (i.e. 0).

    In order for the Division to produce the expected result, you must notify C++ to convert the intermediate result before storage in the destination variable.

    All this is possible using the construct cast. The program, you would write:

    In this case the result of running the program coincides with the wait. In fact, the quotient is calculated as float (the contents of the variable one is forced float) and then, later, assigned to three.

    Ultimately using the unary static_cast applied to the variable one is strength, in the calculation of the expression, its value to be of a specific type (in this case integer division is forced to provide a floating-type result as a value of that type).

    It is now proposed an interesting application of casting for the transformation of a lowercase character uppercase representation. The program leverages to achieve its result, the fact that a variable of type char, ultimately, retains a numeric code; Here it also used the casting to show that code.

    In the line labeled 1 constant is defined. 32 value depends on whether, in ASCII code used in the representation of characters in the memory of a computer, that is the distance between upper and lower case (eg. ' A ' has code 65, ' a ' has code 97).

    In the line labeled 2 you make the character input to process.

    In the line labeled 3 checks if the input character is within the bounds of lowercase letters. Lowercase letters, in ASCII, code between 97 (lowercase a) and 122 (the lowercase letter z). The comparison could also be made on numerical representation:

    If (min > = 97 && min < = 122)

    In the line labeled 4 takes place in practice transformation into uppercase. The numeric code associated with the character is subtracted the value 32. In this case use the numeric code of the character. Note that in this context it makes sense to assign to a char, the result of a subtraction (numerical operation).

    In the line labeled 5 making the output of never intended as a character (so it is in fact defines the variable), where in the row 6 making the output of its numeric code (it used a casting on the variable).

    Introduction to classes and objects: carriers

    The carrier is the first data structure (container, container) treated in computer science. We talk about data structure when referring to a set of data organized according to a specific law. A data structure is a set where, as in the commonly understood mathematics, membership and the law defined whose elements can be carried out certain tasks: creating the structure, inserting/deleting an item, search for an item, select a subset.

    The carrier is the most commonly used data structure and is the one that is the foundation of almost everything else.

    A vector is a collection of variables of the same type that can be accessed through a common name and referencing a specific item by using an index.

    You can think of to the carrier as a series of numbered drawers: a way to access the contents of a drawer is to specify the place where the collection and the number next to the item (index) that indicates their relative position to the starting point of the structure. The first element of the vector has index 0.

    In simple variables to access the value contained in them you must specify the name and, moreover, a variable that has to keep a different value will have a different name. In vector a name exists but this time identifies the entire structure.

    The elements of the vector are allocated in adjacent memory locations.

    C++, in the case of complex structures (container), provides a mechanism (classes) that allows, once declared an object of that type, to the object itself, to possess the typical behaviors of all objects in the same family for easier processing.

    The vector definition is contained in the library vector that must be included in the code as many times as you need to define a variable of type vector. The library is part of what are called the Standard Template Library (STL).

    The differences between the Declaration of a variable of type elementary, for example, a variable of type int, and an object, for example, the vector class can be summed up:

    A type declaration:

    int a;

    acting, for reasons of the kind, defining some operations (the four elementary arithmetic and the module operation) that can be applied to the data contained in the variable that is a container for data on which you want to perform those operations.

    A type declaration:

    vector v;

    declares an object of the class vector containing integers (type is specified between the angle brackets < >) as elements, but v as an object (an instance) of the vector class has all the behaviors defined in the class. You cannot directly manage the elements of the vector because you interact with an object using the methods defined for that class. The method is a skill, a feature that provides a particular processing on the data container. The method relies on the object (it sends a message to the object) and this will react in accordance with the method itself that is, will the items processing described.

    The most common methods of vector class that will be used in examples of these notes are summarised in table:

    Returns a Boolean value (true or false) indicating whether the vector is empty or contains at least one item

    Returns the amount of elements in vector

    Gets the location in memory of the first element of the vector

    Returns the position in memory after the last element of the vector

    Allows you to access the element of the vector that is in a certain position. You must specify the index as integer in parentheses (parameter).

    Allows you to insert, queued in vector, a new item. The element must be specified as a parameter in parentheses and must be of the type provided for in the Declaration of the vector

    Allows the insertion of an element any carrier. In brackets you specify two variables/values (parameters) separated by commas: the pointer to the insertion position, the element to be inserted

    erase method ()

    Eliminates from the structure of an element. Takes as a parameter a pointer to the element.

    A method is applied to the object by specifying it after the name of the object and, separated from this by the operator (the point).

    For example:

    the line of code produces display the amount of items in the vector v.


    The iterator is an object that provides access to individual elements in a container of objects, for example a vector. Using an iterator you can scan linear of a vector, that is, scroll one after the other all items contained in a vector in order, for example, to perform certain processing. An iterator is a pointer to the element (i.e. gives an indication on where is in main memory element) and can be updated according to the rules of arithmetic in to point to the next element of the sequence still consist elements of the sequence.

    As elementary example usage of iterators proposes a code snippet in which, using a sequential scan of a vector of integers, doubles the value of each item contained in it:

    In 1 declares a vector of type int. In 2 you declare an iterator that can iterate through the elements of a vector of the specified type. If there had been a vector of type float, you should define an iterator appropriate: vector :: iterator it.

    The cycle of 3 uses the iterator in accordance with the same rules of integers: is taken as the initial value of the iterator the position of the first element of the array (NUM. begin ()), we then move on to the next item (it ++) until the iterator's value represents a valid position is different, that is, than that returned by end (). Advancing to the next item, in fact, the iterator points to the next element until the value returned by the method.

    Access to the item (4) is obtained using the iterator deferenziando * (* it that is, the element pointed to by it). This way you can operate with the element for example doubles the value in the code proposed.

    You can access the individual element by using the method at (). If for example you want to double the 4 position, which can be coded:

    In this case is used as method parameter, the relative position of the item. You must have the element at the specified location. The index should indicate an existing item.

    In conclusion can be summarized:

    the iterator is used when it comes to sequential access to the elements of the collection

    at () method is used if you need direct access to individual items.

    The method at provides as a parameter an integer (the position of the element) and cannot therefore be used an iterator. However, you can calculate the relative position of an item within the carrier, knowing the value of the iterator that points to the element:

    The position of the element is obtained (1) by subtracting the present value of the iterator (the location in memory of the current item) the position of the first element of the vector. The subtraction between two iterators produces an integer because, as has been noted, iterators, follow the rules of arithmetic. The result of the difference is a number representing how many positions is moved to the current element relative to the position of the first element of the vector.

    Use of vector methods

    To show the applications of other methods of the vector, is offered a program that gained a vector, for example integers, ordered in ascending order, and an integer, put it inside the carrier, in the place it deserves. The program also allows, in the end, deleting an item, you specify the location, away.

    Is the control in 1 that essentially allows you to determine whether the sequence is increasing. If this is the first element (i.e. If i is 0!) or the input is greater than the previously inserted element (the one with index i-1), queues (2). The last condition it would not make sense for the first item but, for the OR operator (| |), just that the first condition is verified to not proceed further. It uses the at to access the previous item.

    If the value entered is greater than the previous one, simply decrementing the loop index (3). This is necessary because, in any case, due to the for construct, the index would be incremented before passing to the control of the cycle. In general it is not a good practice to change, inside a for loop, the variable that controls balance (can lead to errors that are difficult to track down) but here the variable is only used to display the tab order of the element. A better solution might be to use a while loop.

    For the inclusion of items in the vector this time it used a for loop being put 10 items. Otherwise the loop is the same as the input loop treated before.

    Also research the insertion position is formally identical to that considered in previous examples except (4) that here you find the first element of the vector which has greater value of the item to be inserted. The place, in vector, which the new element will be precisely this. If you found an element of the vector is larger than the value to insert (5) fits the element at that position (6). The insert method takes as its first argument an iterator to the position of insertion, which in this case will be the position of the first element of the vector with greater value. If there is no element of the vector, the new value will be appended (7) to those already present.

    Even the erase method for removing an element from the vector, requires an iterator that points to that element. From input (9) you receive the relative position (offset): just (10) add this offset to the value of the pointer to the first element of the vector.

    The cycles of 8 dealing with display effects, in vector, the operations carried out.

    The string class

    Variables of type char allow you to store a single character. If you want to store strings, sequences of characters, such as a word or phrase, you can use the string that contains the class definition string that allows the Declaration of objects of that type.

    The string can be thought of as a vector of char and, from this point of view, an object of this class has all the above methods for a generic vector as, for example, deleting characters inside, access to individual characters that are part of it. An object of type string also has useful methods if the carrier is not a generic vector but a string:

    Positions referenced methods are counted from 0 (position of the first character in the string).

    To facilitate some processing also in examples of these notes should be added, among the features available to string objects:

    For objects of class string is also known as the string concatenation operator +.

    After the steps s3 will contain the string "MalwareTips Forum".

    Example with strings:

    The following program takes a string and a character, and returns the recurrences of the character within the string:

    In order to declare objects of type string, as in 2, include its library (1).

    The input of a string (3) could be made as to elementary variables using the extraction operator from the channel. This is fine if the string supplied as input are not special characters like the space character. In this case, as previously noted, the two parts of the string on the sides of the space would be perceived as two different inputs. Using the getline function can be gained a string containing special characters such as space or punctuation characters up (by default) to Send character terminating the string input. The function you use specifying in brackets at least two parameters: the channel from where to read and the variable to contain the characters from the channel. The third parameter, optional and not used in the examples, specifies the character that is meant as a string terminator. Unless that character is the character enter.

    Assigning a value to a string is performed by means of the usual operator =, you only need to enclose the string between double quotes (where = "test string". In string comparison using the usual operators (<, < =, >, > =, ==,! =).

    The Boolean variable continues, initialized in 4, check out the next cycle.

    The find message, sent in 5 to the string where, in charge of trying the first parameter placed in parentheses, starting from the location specified as the second parameter. The result of this research comes as an integer value that is stored in pos. The starting position is 0 (the first character of the string: pos is initialized to -1 and, as a parameter, you are provided with pos + 1). Subsequent searches will begin at the next location to that found earlier.

    If you do not find further recurrences, the member function find associated with where, provides the value -1 (6), and processing may end: the 7 makes sure to make false the loop control condition.

    Previous article here: [Tutorial] How to start programming in C++ (Part 3)

    Thanks for reading! ;)

    I used Quote function to insert the code, to avoid view problems.
    Wave, kev216, Tornado and 8 others like this.
  2. Razor555

    Razor555 New Member

    Sep 15, 2014
    Goodness me,,, you also teach C++ on MT? :D
    Alkajak, kev216, Rishi and 1 other person like this.
  3. JM Security

    JM Security Level 28

    Apr 12, 2015
    SecureMyBit Developer
    Yes, I made some threads, anyway even if I used Quote function, I don't understand why, when I write "#include..." to import libraries
    there are some problems: when I post the thread, it becomes "#include", without the imported library.
    Alkajak, kev216, CySecy825 and 2 others like this.
  4. Rishi

    Rishi Level 19

    Dec 3, 2015
    Windows 10
    Always a pleasure reading your posts @Jo Man , very informative! Please keep them coming..:)
    kev216, CySecy825 and JM Security like this.
  5. JM Security

    JM Security Level 28

    Apr 12, 2015
    SecureMyBit Developer
    Thanks @Rishi :)
  6. Razor555

    Razor555 New Member

    Sep 15, 2014
    Don't know any languages of that sort so you are asking the wrong person... Plus for the moment I am too lazy to even learn it.. :p
  7. Avra_Neel

    Avra_Neel New Member

    Apr 6, 2016
    Your articles are good...by the way,you may even let users know of some good books to follow,like the C++ Primer,5th Edition, on this subject.It'll help them get a good grasp on the language.
  8. JM Security

    JM Security Level 28

    Apr 12, 2015
    SecureMyBit Developer
    This is a tutorial done by me, not a post to share books links, anyway, maybe I can suggest a good C++ book in the next thread. ;)
Similar Threads Forum Date
Tutorial [Tutorial] How to start programming in C++ (Part 5) Develop Coding Skills - Tutorials Apr 20, 2016
Tutorial [Tutorial] How to start programming in C++ (Part 3) Develop Coding Skills - Tutorials Feb 4, 2016
Tutorial [Tutorial] How to start programming in C++ (Part 2) Develop Coding Skills - Tutorials Jan 27, 2016
  • About Us

    Our community has been around since 2010, and we pride ourselves on offering unbiased, critical discussion among people of all different backgrounds about security and technology . We are working every day to make sure our community is one of the best.
  • Need Malware Removal Help?

    If you're being redirected from a site you’re trying to visit, seeing constant pop-up ads, unwanted toolbars or strange search results, your computer may be infected with malware. We offer free malware removal assistance to our members in the Malware Removal Assistance forum.
  • Quick Tip

    Without meaning to, you may click a link that installs malware on your computer. To keep your computer safe, only click links and downloads from sites that you trust. Don’t open any unknown file types, or download programs from pop-ups that appear in your browser.