Tuesday, 31 March 2015

Function adaptors

Function adaptors with code examples:

Function adaptors work only with function object classes with argument types and result type defined.

Negators:
A negator is a kind of function adapter used to reverse the sense of predicate function objects.
Negators not1 and not2 take a unary and a binary predicate correspondingly and return their complements.

STL-Iterator adaptors in C++

STL-Iterator adaptors in Cpp with code examples:

Reverse iterators:

Bidirectional and random access iterators have corresponding reverse iterator adaptors that iterate through the data structure in the opposite direction. They have the same signatures as the corresponding iterators.
The fundamental relation between a reverse iterator and its corresponding iterator i is established by the Identity
 &*(reverse_iterator(iIndex)) == &*( iIndex - 1)

This mapping is dictated by the fact that while there is always a pointer past the end of an array, there might not be a valid pointer before the beginning of an array.

A copy of the original iterator (the base iterator) is kept internally and used to reflect the operations performed on the reverse_iterator: whenever the reverse_iterator is incremented, its base iterator is decreased, and vice versa. A copy of the base iterator with the current state can be obtained at any time by calling member base.

Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the reversed range).

STL - Container adaptors and the examples in C++

STL - Container adaptors and the examples in Cpp with code examples:

A Container is an object that stores other objects, and that has methods for accessing its elements. In particular, every type that is a model of Container has an associated iterator type that can be used to iterate through the Container's elements.

Each of these "container adaptors" is constructed by taking one of the sequential containers given above and "adapting" its interface to provide the desired behavior.

Stack:
Stack adapts the deque container to provide strict last-in, first-out (LIFO) behavior.

Any sequence supporting operations back, push_back and pop_back can be used to instantiate stack. In particular, vector, list and deque can be used.

Sunday, 29 March 2015

Extern Keyword and Alternate linkage specifications in C++

Extern Keyword and Alternate linkage specifications in Cpp:

In C++ compiler construction, name mangling  or name decoration is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.

Name mangling provides a way of encoding additional information in the name of a function, structure, class or another data type in order to pass more semantic information from the compilers to linkers.

Static member objects in C++

Static member objects in Cpp with code example:

Like static members and Static member functions it is possible to create the static member objects.

See the below example:

Thursday, 26 March 2015

Static member functions implementation in C++

Static member functions implementation in Cpp with examples:

There is possibility that it is possible to create the static member functions that, like static data members , work for the class as a whole rather than for a particular object of a class.
How to call the static member function?

Call a static member function by itself, without any specific object, using the scope-resolution operator.

Syntax of the static member function calling as shown below:

Wednesday, 25 March 2015

Static array initialization In C++ with examples

Static array initialization In Cpp with examples:

we have seen that <give the link to the Static members in C++> static variable<link end> how we have to define inside a class body. Like that it is also possible to create arrays of static objects, both const and non-const.

see the below syntax:

Intersection of circles implementation in C++

Intersection of circles implementation in Cpp:

Two circles may intersect in two imaginary points, a single degenerate point, or two distinct points.
The intersections of two circles determine a line known as the radical line. If three circles mutually intersect in a single point, their point of intersection is the intersection of their pairwise radical lines, known as the radical center.

Intersection cicles

The below sample code tells us how to find the intersection point of the three circles.

Static members in C++

Explain Static members in Cpp with examples:

To avoid the global variables in C, there is concept called static members are introduced in C++.

Why we need Static Variables and Static members?

1. The static variables or members are used to avoid the data modification and the name clashing with the other variables.
2. Using the static data we can allocate single storage space to be used by all objects of a class.
3. There is a single piece of storage for a static data member, regardless of how many objects of that class you create.
4. If the member variable is created as a static, all the related objects of that class can communicate with each other and can share the same static storage space.

What is the scope of the static variable?

The scope of the static variable is inside the class, and we can declare the static member as public, private or protected.

Creating a namespace in C++ with example code

Creating a namespace in Cpp with example code:

A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries.

Using namespace, you can define the context in which names are defined.
The namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier makes it less likely that a name will conflict with names declared elsewhere in the program.

It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier.
Namespace creation is not much difficult, the creation of a namespace is notably similar to the creation of a class

Sunday, 22 March 2015

What are the Operators we can’t overload in C++

What are the Operators we can’t overload in Cpp with examples:

There are some operator that we cannot be overloaded.
The list is below
(Member Access or Dot operator)

?: (Ternary or Conditional Operator )

:: (Scope Resolution Operator)

.* (Pointer-to-member Operator )

sizeof(Object size Operator)

typeid (Object type Operator) 


There is no fundamental reason to disallow overloading of ?:.

Overloading of operator= in C++ with example

Overloading of operator= in C++ with example:

The operator= is confidentially connected to the object on the left side of the ‘=’.
If it was possible to define operator= globally, then you might attempt to redefine the built-in ‘=’ sign:
See the below syntax
int operator=(int, Ourowntype); 

When we create the operator= in our code, we need to copy all the required data from,
Right hand side object into the current object left hand side object to perform whatever
we consider “assignment” for your class.
Let us see the sample example that works on operator=

Overloading of Binary operators with the example

Overloading of Binary operators with the example:

If we want to use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator. Following example explains how addition (+) operator can be overloaded. Similar way, you can overload subtraction (-) and division (/) operators. Again, both global versions and member function versions are shown.

Let us see the below example:

Friday, 20 March 2015

Operator overloading using Unary operators

Operator overloading using Unary operators with examples:

Reading about the operators will not give us a clear picture about overloading of the
Unary operators
Here I am providing the example program which covers catalog of all the unary functions.

Function-call stack frame

Function-call stack frame:

The arguments are stored on the stack when the compiler generates the code for a function and then only it will call the function. The code is generated to move the stack pointer down even farther to provide storage for the function’s local variables.

But during the assembly-language CALL, the CPU pushes the address in the program code where the function call came from, so the assembly language RETURN can use that address to return to the calling point. This address is of course sacred, because without it your program will get completely lost. Here’s what the stack frame looks like after the CALL and the allocation of local variable storage in the function.

Passing & returning by value using the copy constructor

Passing & returning by value using the copy constructor:

The copy-constructor supports passing and returning values.

Let us see the C language how it is handling passing and returning variables by value during function calls.
See the sample  code

int MyFunction(int iVal, char chTemp);
int iResult = MyFunction(iVal1, chTemp1);

how does the compiler know how to pass and return those variables? It just knows! The range of the types it must deal with is so small – char, int, float, double, and their variations – that this information is built into the compiler.

If you figure out how to generate assembly code with your compiler and determine the statements generated by the function call to MyFunction ( ), you’ll get the equivalent of:

Bitcopy versus initialization in C++

Bitcopy versus initialization in Cpp with examples:

So far, so good. There’s a workable process for passing and returning large simple structures. But notice that all you have is a way to copy the bits from one place to another, which certainly works fine for the primitive way that C looks at variables. But in C++ objects can be much more sophisticated than a patch of bits; they have meaning. This meaning may not respond well to having its bits copied.

Consider a simple example: a class that knows how many objects of its type exist at any one time. We know that we can do this by including a static data member.

Dynamic Object Creation in C++

Dynamic Object Creation in Cpp with examples:

Sometimes it is required that we need to create the objects dynamically and also it is required that we need to destroy them at the runtime.

Using C there are two dynamic memory allocation functions, 1. malloc () and 2. free () , that allocate storage from the heap which is also called the free store at runtime.

Coming to the C++ the constructor does not allow us to hand it the address of the memory to initialize, and for good reason.

 If you could do that, you might:

1. Then guaranteed initialization of objects in C++ wouldn’t be guaranteed.
2. Accidentally do something to the object before you initialize it, expecting the right thing to happen.
3. Hand it the wrong-sized object. And of course, even if you did everything correctly, anyone who modifies your program is prone to the same errors.

Monday, 16 March 2015

C++ References in functions with examples

C++ References in functions with examples:

References are frequently used as  function arguments and function return values. When a reference is used as a function argument, any modification to the reference inside the function will cause changes to the argument outside the function.

  If you return a reference from a function, you must take the same care as if you return a pointer from a function. Whatever the reference is connected to shouldn't go away when the function returns, otherwise you’ll be referring to unknown memory.

Let us see the working example to understand about the references used like arguments and return values.

References in C++ with examples

References in C++ with examples:

In C++ the reference is nothing but the pointer that is automatically dereferenced.
The areas that references used as shown below.
1. Function argument lists.
2. Function return values.

int igVal;

int& iGRef = igVal;  // When a reference is created, it must be initialized to a live object.

const int& iCRef = 10;


Friday, 13 March 2015

Searching in strings

Searching in strings with examples: 

C++ strings supports finding the required string content from the total string.

Here is the list available find functions.

1. find ( ) : It searches a string for a specified character or group of characters and returns the starting position of the first occurrence found or npos if no match is found.
2. find_first_of ( ): This function searches a target string and returns the position of the first match of any character in a specified group. If it finds no such element then it returns npos.
3. find_last_of ( ): This function searches a target string and returns the position of the last match of any character in a specified group. If it finds no such element then it returns npos.
4. find_first_not_of ( ) : This function searches a target string and returns the position of the first element that doesn’t match any character in a specified group. If it finds no such element then it returns npos.
5. find_last_not_of ( ): This function searches a target string and returns the position of the element with the largest subscript that doesn’t match of any character in a specified group. If it finds no such element then it returns npos.
6. rfind ( ): This function searches a string from end to beginning for a specified character or group of characters and returns the  starting position of the match if one is found. If it finds no such element then it returns npos.

Thursday, 12 March 2015

C++ Strings creation and initialization with examples

C++ Strings creation and initialization with examples:


Creating and initializing strings is a direct scheme, and flexible as well.
I just want to tell the same this using the below example.
The first string, Str1, is declared but contains no initial value. Unlike a C char array, which would contain a random and worthless bit pattern until initialization, Str1 does contain valid information. This string object has been initialized to hold “no characters,” and can properly report its 0 length and absence of data elements through the use of class member functions.

The next string, Str2, is initialized by the literal argument "Where are my socks?". This form of initialization uses a quoted character array as a parameter to the string constructor. By contrast, Str3 is simply initialized with an assignment. The last string of the group, Str4, is initialized using an existing C++ string object.

See the below sample code to understand the initialization of the strings.
1. Create an empty string and defer initializing it with character data
2. Initialize a string by passing a literal, quoted character array as an argument to the constructor
3. Initialize a string using ‘=‘
4. Use one string to initialize with another string

Wednesday, 11 March 2015

Strings in C++, what is the difference between C++ Strings and the C character array

Strings in C++, What is the difference between the C++ Strings and the C character array:

The biggest drawback in   C is character array. The difference between the strings and array is one created in stack and another is created in heap.  In addition, the known thing that in some situations we have to pass the char* and some other situations we must copy the whole array. The memory allocated for the Strings in the heap location.
So the memory is allocated dynamically.

As a programmer, we have keep concentrating on the string manipulations, because these are the sources of the bugs.
Coming to the class, which contains character pointer may leads to crash the application by the shallow copying and the deep copying of the member data.

To overcome these problems string library is introduced to C++ programmers. The String library class can resolve the problems occurred while using the char* and character arrays. The string function keeps the track of the memory while using copy constructors.

In this post we first learn the introduction to the strings, and coming posts we will learn the operations on the strings.

Tuesday, 10 March 2015

Find the address of a function template

Find the address of a function template:

If we want to find the address of the function at any situation, there are number of ways available in C++.

For example, you may have a function that takes an argument of a pointer to another function. Of
course it’s possible that this other function might be generated from a template function.
See the below example to find the address of the function template.

Allocate the memory for Templates in C++

Allocate the memory for Templates in Cpp with examples:

As we learned in the previous post,  C style memory allocation is done using the raw functions called as malloc( ), calloc( ), realloc( ) safer.

See the below function template produces one function GetMemory ( ) that either allocates a new piece of memory (using malloc)or resizes (using realloc) an existing piece  In addition, it zeroes only the new memory, and it checks to see that the memory is successfully allocated.

In this program we have to provide the number of elements of the type you want to allocate, not the number of bytes, so the possibility of a programmer error is reduced.

Templates in C++ with examples

Templates in Cpp with examples:

The main aim of templates are to allow the function or class to work in different data types without being rewritten for each one.

There are three types of templates available in C++ as shown below

Function templates
Class templates
variable templates

Function templates:

In C++, function templates are behave like functions that serve as a pattern for creating other similar functions. The basic idea behind function templates is to create a function without having to specify the exact type(s) of some or all of the variables. Instead, we define the function using placeholder types, called template type parameters.

Monday, 9 March 2015

Virtual base class initialization and the most derived classes


Virtual base class initialization and the most derived classes with examples:

That means any class, no matter how far away it is from the virtual base, is responsible for initializing it.

See the working example to understand more about the most derived classes.

Type casting with different types of type casting techniques

Type casting with different types of type casting techniques with examples:

 Typecasting is the technique that is used to convert the data explicitly.
See the below example, in this example we are converting double to integer value
#include "stdafx.h"
#include <iostream>
using namespace std;
int main ()
{
  double dData = 100.90;
  int iVal = 0;
  iVal = int (dData);
  iVal = (int) dData;
  getchar ();
  return 0;
}   

The functionality of these generic forms of type-casting is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that -while being syntactically correct- can cause runtime errors.
For example, the following code compiles without errors:

Run-time type identification (RTTI)

Run-time type identification (RTTI) with examples:

Using RTTI(Run time type identification) we can find the exact type of the object
The RTTI is useful when the when exception handling was added to C++, When exception handling was added to C++, it required the exact type information about objects. It became an easy next step to build access to that information into the language.

Let us see the simple “Shape” example:

This is an example of a class hierarchy that uses polymorphism. The generic type is the base
Class Shape, and the specific derived types are Point, Line, and Area:
polymorphism example

Friday, 6 March 2015

Inheritance and access specifiers

Inheritance and access specifiers with examples:

There are three types of inheritances available in inheritance.

Types of Inheritance
We have seen there are three types of access specifiers in C++.

 Like that there are three types of access specifiers available for inheritance. See the above diagram.
As we know that the public members can be accessed by anyone, and the private members can only be accessed by member functions of the same class.

Let us see the simple example to understand quickly about the access specifiers:

Thursday, 5 March 2015

Dangling Pointers with examples

Dangling Pointers in cpp with examples:

Dealing with the memory is the most important task for the programmer. Some cases we may face some problems like the application runs 10 times and it crashes 3 times out of 10. We do not predict the problem that we are getting, to track that problem we will search for another way. That is we will decide to run that application in different machines.

In this situation also we get the result like that the application may run in 5 systems out of 8, the remaining 3 systems application may crash.

Nine times out of ten, when you're told that a program 'sometimes crashes', those crashes are random, and apparently they do not depend on a particular user's action. This one is no exception.

If this situation come I will go and search for some major points.

1. A memory allocation (malloc, calloc, strdup, and realloc) returns NULL, and this return value is ignored.
2. A resource allocation (fopen, or CreateFile, for instance) returns NULL (or INVALID_HANDLE_VALUE), and this return value is ignored.
3. A race condition: one thread is trying to use a resource that was released by another thread.
4. A memory corruption, for instance a buffer overflow.
5. A dangling pointer.

Wednesday, 4 March 2015

Smart pointers -Shared_ptr , week_ptr, unique_ptr and auto_ptr

Smart pointers -Shared_ptr , week_ptr, unique_ptr and auto_ptr with examples:

Smart pointers are the abstract data types , these can handle the major memory problem that occurred in the code. These smart pointers track the memory that they are pointing to. As we know that the majority of bugs happens in the code because of bad memory management. Smart pointers will take care of these type of problems and they deallocate the memory automatically. Smart points eliminates the dangling pointers.

Now look into the each type of pointer.

unique_ptr:

This pointer is available in #include
 &ltmemory&gt


A unique_ptr is a container for a raw pointer, which the unique_ptr is said to own. A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), but the std::move function can be used to transfer ownership of the contained pointer to another unique_ptr. A unique_ptr cannot be copied because its copy constructor and assignment operators are explicitly deleted.

Tuesday, 3 March 2015

Difference between ++*ptr and *ptr++ with examples

Difference between ++*ptr and *ptr++ in Cpp with examples and pictorial representation:

We have to first think that the meaning of the *ptr, it is pointing to the value that is being located at the address location.

Then we have to consider the below points.

++*ptr: means the value that is pointing to particular location is incremented by one.
Which is equal to pre-increment operation

*ptr++:means that the value that is pointing to the particular address location is incremented by one.
Which behaves like the post-increment operator.

Let us see the example below:

Here we assume that the address of the integer value is 5000.

The void pointer (void*) in Cpp with examples

The void pointer (void*) in Cpp with examples

The void pointer is also a pointer that points to anything which not known at the declaration time. Or in other words a void* pointer is a pointer that point to a value that has no type. A void pointer seems to be of limited use. However, when combined with the ability to cast such a pointer to another type, they are quite useful.

The void* has an  undetermined length and undetermined dereference properties, void pointer can point to any data type, from an integer value or a float to a string of characters. That's why it is also referred to as a generic pointer.

For example a function that’s returning value is void* means that can be doing the below operations

Case1: Unformatted memory: This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type

Case2: It is an opaque handle: it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.

Monday, 2 March 2015

The VTABLE in C++ with examples

The VTABLE in C++ with examples:

The VTABLE in C++ is having different names. We can call it as virtual method table, virtual function table, virtual call table, Dispatch Table or vtable. The VTABLE is used to support the runtime method binding or dynamic dispatch.

The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.

When the compiler founds that, there is the virtual function in the class it implements the hidden pointer that points to the VTABLE. So the VTABLE contains the array of pointers to the virtual functions, the actual function will call at the run time through these pointers.

The virtual table is created at the compile time and the table is created for every class that contains virtual function or the class that is derived from the class that uses the virtual functions. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.

Virtual Pointer:
The VPTR is the pointer that is created by the compiler to access the vtable. Initially it is created for the MyBase calss. And then at run time when the instance is created that points to the vtable of the required calss.