Sunday, 22 November 2015

Design Pattern - Command Pattern in C++

Design Pattern - Command Pattern in Cpp with code examples:

Purpose of the command pattern:

This pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.

For example, SwitchOn object has the right method (execute(), and actually, doing Switch->On()) of the receiver (Switch object). This is possible, the command object has the pointer to the Switch receiver as its member. So, when asked to perform an action on a receiver, we just feeding the command object to the invoker.

The invoker which is named as control in the code make a request of a Command object by calling
that object's execute() method. Then, since the method knows what the receiver is, it invokes the action on that receiver.

Here is an example code:

Will update the code later

Output from the run:
The Switch is on
The Switch is off

Design Patterns - Strategy Pattern in C++

Design Patterns - Strategy Pattern in C++:

Introduction:
This pattern is used to encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.


Design patterns - Chain of Responsibility in C++

Design patterns - Chain of Responsibility in Cpp with code examples:

This post will explains you how the objects are processing. For example, Filter/ColorMatch/RedEye/Rotator is the processing objects.



Wednesday, 12 August 2015

How to use gdb tool to generate core file caused by Segmentation fault

How to use gdb tool to generate core file caused by Segmentation fault :

First of all we need to know about what is segmentation fault? When the segmentation fault will occur?

A program that is trying to access unauthorized memory location caused the segmentation fault.
The segmentation faults occurred by different reasons as shown below.

Improper use of pointers in the source code, let us see the sample code.

Here is the file to generate the core file. The code is dereferencing a NULL pointer in SegFaultTest (), and when we run, it gives us core file.

Monday, 3 August 2015

STL - Vector vs List differences in C++


STL:Vector vs List differences in Cpp with examples

Vector:

1. Vector is similar to array
&v[i] == &v[0] + i; 

2. vectors allocates contiguous memory.
3. Vectors allocates memory space at the time of declaration for future elements, in future extra space may be required.
4. Compared to the list here additional space for a pointer is needed, each element only requires the space for the element type itself.
5. Vectors re-allocate memory for the entire vector at any time that we add an element.
6. Insertions at the end are constant. And the insertions at any place are costly O(n).
7. Erasing an element at the end of the vector is constant time, but for the other locations it's O(n).
8. Another advantage for the vector is it provides random access of its elements.
9. Iterators, pointers, and references are invalidated if we add or remove elements to or from the vector.

Sunday, 21 June 2015

Methods of choosing overloading vs. default arguments in C++

Methods of choosing overloading vs. default arguments in Cpp with example:

Both function overloading and default arguments provide a convenience for calling function names. However, it can seem confusing at times to know which technique to use. For example, consider the following tool that is designed to automatically manage blocks of memory for you:

Efficient Use of Destructors to Prevent Resource Leaks with examples in C++

Efficient Use of Destructors to Prevent Resource Leaks with examples in Cpp with example

When the exception thrown by a program that is not caught, program execution immediately stops.
In C language this situation is handled by setjmp and longjmp.
The longjmp behaves differently with the C++ language. It fails to call destructors for local objects when it adjusts the stack.

How to use destructors to prevent resource leaks?

Yes, we need to learn about this clearly, to avoid memory leaks.
A reasonable approach to this task is to define an abstract base class, ANIMAL, plus concrete derived classes for Dogs and Cats. A virtual function, process property, and handles the necessary species-specific processing:

Thursday, 18 June 2015

Reading data from CSV file and writing it into the PostgreSQL database in C++

Reading data from CSV file and writing it into the PostgreSQl database in Cpp with examples:

In this we are going to learn how we are using Postgres database using the languages C/C++.

First of all we need to understand the procedure and the functions used in Postgress database creation and manipulation etc.

APIS that are used to work with tPOSTGresSql data base:

To access the database from your C/C++ program, we are going to use a library called libpq-fe. The most basic functions that we'll need in order to access the database are the following:

PQconnectdb – makes the connection to the database
PQexec – executes the required queries
PQgetvalue – get the required values

#include <postgresql/libpq-fe.h>
,we need to include the header file into the application, where we are going to use the Postgres database related functions

Declare the connection with the PostGreSql:

Template Arguments versus Template Parameters

Template Arguments versus Template Parameters

In this post I would like to clarify what is the difference between the template arguments and template parameters. Here is the sample syntax
template <Type T, int iIndex>

class ArrayInClass {

  public:

    T TempArrayObj[iIndex];

};


The below is the sample plain class.

Abstract factories in C++ with example

Abstract factories in Cpp with example

The Abstract Factory pattern looks like the factory objects we have seen previously, with not one but several factory methods.
Each of the factory methods creates a different kind of objects.

The idea is that at the point of creation of the factory object, you decide how all the objects created by that factory will be used.

Here is an example suppose you are creating a general-purpose gaming environment and you want to be able to support different types of games. Here is how it might look using an abstract factory:

Polymorphic factories

Polymorphic factories in Cpp with examples

The static factory( ) method in the previous example forces all the creation operations to be focused in one spot, to that’s the only place you need to change the code. This is certainly a reasonable solution, as it throws a box around the process of creating objects. However, the Design Patterns book emphasizes that the reason for the Factory Method pattern is so that different types of factories can be subclassed from the basic factory (the above design is mentioned as a special case). However, the book does not provide an example, but instead just repeats the example used for the Abstract Factory. Here is ShapeFactory1.cpp modified so the factory methods are in a separate class as virtual functions:

Multiple dispatching in C++

Multiple dispatching in Cpp with examples

AS of we know that C++ performs only single dispatching.
That is, if you are performing an operation on more than one object whose type is unknown C++ can invoke the dynamic binding mechanism on only one of those types.

The solution for the above problem is multiple dispatching.

Remember that polymorphism can occur only via member function calls, so if you want double dispatching to occur, there must be two member function calls: the first to determine the first unknown type, and the second to determine the second unknown type.

With multiple dispatching, you must have a virtual call to determine each of the types.

 Here is a working example for multiple dispatching:

Visitor Design Pattern

Visitor Design Pattern in Cpp with examples:

This pattern is a type of multiple dispatching.

It is possible to add the new polymorphic methods to that hierarchy, which means that normally you would have to add something to the base class interface.

The visitor pattern allows you to extend the interface of the primary type by creating a
Separate class hierarchy of type visitor to virtualize the operations performed upon the
Primary type.

The objects of the primary type simply “accept” the visitor, then call the visitor’s dynamically-bound member function.

The below is the example for visitor design pattern.

Global scope resolution

Global scope resolution in Cpp with example.

This post will give the clarification about the Global scope of the variables.
The scope resolution operator gets you out of situations in which the name the compiler chooses by default is not what you want.

For example, suppose you have a structure with a local identifier iVal, and you want to select a global identifier iVal from inside a member function. As usual, the compiler would default to choosing the local one. Otherwise, we so must tell it to consider the global variable.

When you want to specify a global name using scope resolution, you use the operator with nothing in front of it.

Here is an example that shows global scope resolution for both a variable and a function:

Nested structures in CPP with examples

Nested structures in CPP with examples:

Yes, it is possible to write the nested structures within another structure.

The declaration syntax is what you would expect, as you can see in the following structure.
The below program represents the pushdown stack as a simple linked list so it “never” runs out of memory:

Wednesday, 8 April 2015

Frequently used String operations in C & C++

Frequently used String operations in C & Cpp with code examples:

So, the below are the some of the working and perfectly tested common string operations, that we have used in our projects.

GetStrLength
Strdup
AddString2List
GetCount
Destroy
StrTokenizeCmplx
Strcpy
StrEqual
FindStrEqualn
MakeStrLower

Sunday, 5 April 2015

Linked list implementation using Templates in C++

Linked list implementation using Templates in Cpp:

Working example for different operations on the linked list using the templates. The below is the header file of the linked list contains below list of functions

Insert: this function is used to add the new node into the list.
Delete: this function is used to delete the requested node from the linked list
Search: this function is used to search the node requested node from the linked list
Reverse. This function is used to reverse the linked list.

Sort: This function is used to sort the list using merge merge sort algorithm
Merge: This function is used to merge the sorted nodes in the list.

Double linked list example code in C++ using templates


Double linked list example code in Cpp using templates:

The below listed functions are used to manipulate the double linked list.

GetHeadNode: This function gets the head node from the list.
GetLastNode: This function gets the last node from the list.
GetCount (): This function gets the number of nodes in the list.
AddNode:This function adds the new node nto the list.
RemoveAt: This function remove the node at the given index.
GetAt:This function gets the node at the given index.
Destroy:This function destroys the entire list.

Wednesday, 1 April 2015

Basics of Linked Lists in C++

Basics of Linked Lists in Cpp with code examples:

A linked list is a data structure consisting of a group of nodes which together represent a sequence. Linked lists are used to store collections of data. The specific type of element is not important since essentially the same structure works to store elements of any type.

Each node is composed of a data and a reference to the next node in the sequence. More complex variants add additional links. Each node contain two fields: an integer value and a link to the next node.

The last node is linked to a null terminator used to signify the end of the list.


Convert the Decimal value to the binary in C++

Convert the Decimal value to the binary in Cpp with code example:

We can convert the decimal values to binary values in two different ways
In this example one we need to include the iomanip to convert decimal to binary
#include <iomanip> 


Unsigned & signed integers implementation in C++

Unsigned & signed integers implementation in Cpp with code example:

The below program gives us to identify how the difference between signed and unsigned integer affects the loops when they are used as loop variables.

Setting and clearing the bit in C++:



Setting and clearing the bit in C++:

#include <iostream>

using namespace std;

bool GetBitVal(int Num, int iIndex)
{
 return ( (Num & (1 << iIndex) ) > 0);
}

int SetBitVal(int Num, int iIndex, bool b)
{
 if(b)
  return (Num | (1 << iIndex)) ; 
 else {
  int mask = ~(1 << iIndex);
  return Num & mask;
 }
}

int main ()
{
 int iNumber = 0, iIndex = 0;

 iNumber = 20;

 cout << "Input" << endl;
 for (int iInd = 7; iInd >= 0; iInd--) 
  cout << GetBitVal(iNumber,iInd) << " ";
 cout << endl;

 /* set bit */
 iIndex = 4;
 cout << "Setting " << iIndex << "-th bit" << endl;
 iNumber = SetBitVal(iNumber, iIndex, true);
 for (int iInd = 7; iInd >= 0; iInd--) 
  cout << GetBitVal(iNumber,iInd) << " ";
 cout << endl;

 /* unset (clear) bit */
 iIndex = 5;
 cout << "Unsetting (Clearing) " << iIndex << "-th bit" << endl;
 iNumber = SetBitVal(iNumber, iIndex, false);
 for (int iInd = 7; iInd >= 0; iInd--) 
  cout << GetBitVal(iNumber,iInd) << " ";
 cout << endl;
  getchar ();

 return 0;
}
Output of the above program is:
Input
0 0 0 1 0 1 0 0
Setting 4-th bit
0 0 0 1 0 1 0 0
Unsetting (Clearing) 5-th bit
0 0 0 1 0 1 0 0

Bitwise operators with examples in C++

Bitwise operators with examples in Cpp with code examples:

Byte is the lowest level at which we can access data; there is no "bit" type.
And also it is not possible to perform operations on a single bit -- every bitwise operator will be applied to, at a minimum, an entire byte at a time.

Using bitwise operators, it is possible to write functions that allow us to compact 8 Booleans into a single byte-sized variable, enabling significant memory savings at the expense of more complex code. In the past, this was a good trade-off. Today, at least for application programming, it is probably not.

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.

Wednesday, 25 February 2015

Different types of Design patterns and the differences between them

Different types of Design patterns and the differences between them:

Design patterns divided into three groups.

Now let us see about each one, and where exactly these are useful:

Creational Design pattern:

These patterns are useful when we want to create the object of the particular class that is the solution for our problem.  I .e when we try to take the decision of the class that we want to access at the run time instead of the compile time.

Creational patterns support the creation of objects in a system. Creational patterns allow objects to be created in a system without having to identify a specific class type in the code, so you do not have to write large, complex code to instantiate an object.

 It does this by having the subclass of the class create the objects. However, this can limit the type or number of objects that can be created within a system.

Thursday, 19 February 2015

Adapter Design pattern with example

Adapter Design pattern with examples:

Adapter Pattern comes under the Structural pattern.
Adapter Design pattern work as the bridge between the two incompatible interfaces. I.e. it converts the interface of a class into another interface that clients expect.

What are the uses of the Adapter pattern?
This pattern is used when we need an existing class, and its interface does not match the one we need.

It is also use when we want to create a reusable class that cooperates with unrelated classes, that is, classes that do not necessarily have compatible interfaces.

And also where we need to use several existing subclasses, but it's impractical to adapt their interface by sub classing every one. An object adapter can adapt the interface of its parent class.

In real time example could be a case of card reader, which acts as an adapter between memory card and a laptop. When we plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

Let us see the simple example that helps us to understand more:

Tuesday, 17 February 2015

Proxy Design Pattern with example

Proxy Design Pattern with examples:

The proxy pattern is the one of the design pattern. This is anything that signifies the network connection, a large object in the memory etc.

What is Proxy?
Proxy means that the object represents like another object or in other words, it provides the replacement for another object to control access to it.

Where the proxy pattern used?
The proxy patterns are used where multiple copies of the objects exist. For example there is one complex class needs to be used in many places, using the multiple proxy objects we can access the single complex class object reference. That is all the proxy class objects are forwarded to the one complex class object. The memory for the complex class object gets deleted after all the proxy objects are out of scope.
proxy design pattern

Monday, 2 February 2015

How to print the Floyd's triangle in C? Explain with examples.

Please explain how to print the Floyd's triangle in C with examples:

This is also one of the basic interview questions for the fresher’s.

This  is a right-angled triangular array of natural numbers, used in computer science education. This  Floyd's triangle is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner
1

2 3

4 5 6

7 8 9 10

11 12 13 14 15


Here is the example program to print the Floyd's triangle in C.

Pattern printing in C with examples

Pattern printing in C with examples:

DCBA

 CBA

  BA

   A


The below code helps to print the above format

Get the maximum occurrence of the character in the string with example in C/C++


Get the maximum occurrence of the character in the string with example in C/Cpp:

Here Input string = “test string for testing”

Constructing the character count array from the input string.

  iCount['e'] = 2
  iCount['s'] = 3
  iCount['t'] = 5
  iCount['r'] = 2
  iCount['i'] = 2
  iCount['f'] = 1
  iCount['o'] = 1
  iCount['f'] = 1
  iCount['n'] = 2
  iCount['g'] = 1

In the above array we can get the maximum number is ‘5’ that is ‘t’

Wednesday, 28 January 2015

Function pointers with overloaded function in C++ with example

Function pointers with overloaded function in C++ with example:

The use for function pointers is setting up "listener" or "callback" functions that are invoked when a particular event happens. The function is called, and this notifies your code that something of interest has taken place.

The overloaded functions are perform in the following seven contexts.

1) The initializer in a declaration of an object or reference
2) It is on the right-hand-side of an assignment expression
3) It is like a function call argument
4) as a user-defined operator argument
5) the return statement
6) explicit cast or static cast argument
7) non-type template argument

In each context, the name of an overloaded function may be preceded by address-of operator & and may be enclosed in a redundant set of parentheses.

Tuesday, 27 January 2015

Reversing the Linked List in C/C++ with examples

Reversing the Linked List in C/Cpp with example:

There are two ways to reverse the linked list:

1. We need to know more about the pointers or we have more knowledge on pointers.

2. Swapping starts from the first node’s object and the first node’s object is swapped with the last node’s object. Then, the second node’s object is swapped with the one before the last node’s object.

Monday, 26 January 2015

Reading the XML file in C++ with example

Reading the XML file in Cpp with example:

What Is XML?

As we now that XML is merely a syntax for describing data. Outside of a specific application, XML data has no meaning.
XML documents form a tree structure that starts at "the root" and branches to "the leaves".

Simple XML file example is
<?xml version="1.0" encoding="UTF-8"?>

<Address>

    <name>dhruthi</name>

     <plotno>G16/A, 306, Swarna Complex</ plotno >

     <Street>Near M.G.N school</Street >

     <District>Rangareddy</District>

</ Address >


Friday, 23 January 2015

Factory design pattern in C++ with example

Factory design pattern in C++ with example:

What is the factory pattern?

Let us see overview of the factory pattern:

Factory in real life constructs tangible objects, such as tables, cars and languages.
Like that, a factory in object-oriented programming constructs objects. When you use factories in your program, portions of code that want to create a particular object ask the factory for an instance of the object instead of calling the object constructor themselves.

For example, an interior decorating program might have a CarFactory object.

When part of the code needs a type of car such as a innova, it would call the buyCar() method of the CarFactory object, which would return a new car.

At first glance, factories seem to lead to complicated designs without clear benefits.

It appears that you’re only adding another layer of complexity to the program. Instead of calling buyCar () on a CarFactory, you could simply buy a new car object directly.

However, factories can actually be quite useful. Instead of creating various objects all over the program, you centralize the object creation for a particular domain. This localization is often a better model of real-world creation of objects.

Thursday, 22 January 2015

Singleton design pattern in C++ With example

Singleton design pattern in Cpp with example:

We can use single object of the class throughout the lifetime of an application using singleton design pattern.

To get a single object is by declaring a class, which contains only static methods. Then the static class is loaded into the memory when the program execution starts and still available until the application ends. If there is situation that we need only one instance of a class in a truly object oriented fashion by adhering to the basic principles of object oriented programming, the Singleton patterns are used.

The Singletons are often used to control access to resources such as database connections or sockets.

Suppose we have a license for only one connection for our database. A Singleton connection object makes sure that only one connection can be made at any time.

Tuesday, 20 January 2015

Merging of two files in C/C++ with examples

Merging of two files in C/Cpp with examples:

To copy the data from one file store it into the another file is called as merging of two files.

These are the steps that we need to follow while merging of two files.
1. Open the files1 and file2 in the read mode
2. Read the character by character and store it into another file.

Let us see the below example code and run it.

File Operations in C/C++ with examples

File Operations in C/Cpp with examples:

A file that represents the sequence of bytes that are stored on the disk, where the group of related data is stored.

A file is used for permanent storage of the data. In C we have some predefined file operations.
The list is shown below


Function
description
fopen()
Tis function creates a new file or open a existing file
fclose()
This function is used to close a file
getc()
This function is used to read a character from a file
putc()
This function is used to write a character to a file
fscanf()
This function is used to read a set of data from a file
fprintf()
This function is used to write a set of data to a file
getw()
This function is used to read a integer from a file
putw()
This function is used to write a integer to a file
fseek()
This function is used to set the position to desire point
ftell()
This function is used to give the current position in the file
rewind()
This function is used to set the position to the beginning point

For fopen function we have different types of mode available to open the file, Please see the below list

Implementation of the Binary tree in C++ working code and tests

Implementation of the Binary tree in Cpp working code and tests:

From the previous posts we have seen the different possible problems and the solutions related to the binary trees.

Some of those are
Creating the binary tree [Creating the binary tree and find the size in C++ with examples]
Binary tree Traversals (in-order, pre-order & post- order)[ Binary Search tree in C++(BST) with examples]
Finding the size of the existing binary tree [Creating the binary tree and find the size in C++ with examples]
Inserting the data into the binary tree [Explain inserting the data into the Binary Tree in C++ with code examples ]
Finding maximum depth [Finding the maximum and minimum depth of the binary trees in C++ with examples]
Finding the minimum depth [Finding the maximum and minimum depth of the binary trees in C++ with examples]
Finding the total sum of the path of the Binary Tree [Finding the sum of the path of Binary tree in C++ with examples]
Finding the mirror of the tree [Finding the mirror of the binary tree with the solution in C++ with example]
Doubling the tree [Double the binary tree with the example in C++] etc.

Now, we can find the working code of the binary search tree.

Monday, 19 January 2015

Double the binary tree with the example in C++

Double the binary tree with the example in Cpp:

For each node in a binary search tree, create a new duplicate node, and insert the duplicate as the left child of the original node.
The resulting tree should still be a binary search tree.

See the below sample tree
Sample tree

 After doubling the tree the result is

Double the tree

Finding the mirror of the binary tree with the solution in C++ with example


Finding the mirror of the binary tree with the solution in Cpp and explain with examples:


The mirror of the binary tree means change a tree so that the roles of the left and right pointers are swapped at every node. Let us consider the sample example tree.

             14

             / \

            12  15

           / \

         11  13  


is changed to...
                              14

                             / \

                            15  12

                           / \

                          13   11



Sunday, 18 January 2015

Finding the sum of the path of Binary tree in C++ with examples

Finding the sum of the path of Binary tree in Cpp with examples

Let us create a tree as shown below that is a sequence of nodes in the tree starting with the root node to leaf, as we know that leaf node means that node that has no children. And also the empty tree contains no leafs, So there is no possibility of the root-to-leaf paths.

See the below example tree that contains four root-to-leaf paths.

You can see the previous post to insert the data into the binary tree [Explain inserting the data into the Binary Tree in C++ with code examples]
      6

    /    \

  4    12

  /    /    \

10  13  4

/  \     \

8 2    12



The possible Root-to-leaf paths shown below

Friday, 16 January 2015

Finding the maximum and minimum depth of the binary trees in C++ with examples

Finding the maximum and minimum depth of the binary trees in Cpp with examples:

As we have seen before post we have bit knowledge about creating, inserting and getting size of the binary trees.

GetMaximumDepth()
Given a binary tree, compute its "GetMaximumDepth" -- the number of nodes along the longest path from the root node down to the farthest leaf node.

Syntax of the function is

int GetMaximumDepth(struct node* node)


Here we are passing root node as an argument. It returns the maximum depth.

GetMinimumDepth()

Given a non-empty binary search tree, return the minimum data value found in that tree.
Note that it is not necessary to search the entire tree.

Note:This can be solved with recursion or with a simple while loop.

Thursday, 15 January 2015

Explain inserting the data into the Binary Tree in C++ with code examples

How to Insert the data into the Binary Tree in Cpp:

Here we are going to learn how to insert the new node into the binary tree.
I hope that you were remembered the previous post about the binary trees and the syntax of the binary tree. What is the binary tree? What is the structure of the binary tree and so on.

You can find more information on Binary Trees here.

InsertNewNode() – This function helps us to understand how to insert a new node with the given number into the tree in the in the correct place. The InsertNewNode() code modifies the tree structure.

The InsertNewNode() returns the new tree pointer to use to its caller. Calling InsertNewNode() with the number 4 on this tree.


Newly Inserted Node

Creating the binary tree and find the size in C++ with examples

Creating the binary tree and find the size in Cpp:

First, we will look into the solution to create the binary tree:

This is a very basic problem with a little pointer manipulation. Write code that builds the following little 4-1-3 binary search tree.

4-1-3 binary tree view


Monday, 12 January 2015

Binary Search tree in C++(BST) with examples:

Binary Search tree in Cpp(BST) with examples:

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element.

The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees”.

Empty tree: A null pointer represents a binary tree with no elements -- the empty tree.
The formal recursive definition is: a binary tree is either empty, or is made of a single node,

Where the left and right pointers (recursive definition ahead) each point to a binary tree.
They differentiate only with one feature that is the organization of the data.

Here is the small example that helps us to understand the binary tree
A binary tree is a tree that is limited such that each node has only two children.

Sunday, 11 January 2015

Comparison of a float with another value in C

Comparison of a float with another value in C:

Find out the output of the below program
#include <iostream>
using namespace std;
int main (int nNumberofArgs, char* pszArgs[])
{
    float fVal = 1.2;
    if (fVal == 1.2)
        printf("I am in the IF condition");
    else if (fVal == 1.2f)
        printf("I am in the ELSE IF condition");
    else
       printf("iam in the ELSE condition");
  return 0;
}


Friday, 9 January 2015

Pointers in C++ with examples

Pointers in Cpp with examples:

Pointers are very easy in C++. If we understand correctly we can play with the pointers, otherwise they will play with us. As a C++ developer, we have to know about the pointers.
When we define a variable, the memory allocated for that and that memory location have its address. That address can be accessed using & operator, which defines the address in the memory location.
 Let us look into the following program, which will print the address of the variables defined:
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
   int  iVal1;
   char iVal2[10];
   cout << "Address of iVal1 is: ";
   cout << &iVal1 << endl;
   cout << "Address of iVal2 is: ";
   cout << &iVal2 << endl;
   return 0;
}