Monday, February 22, 2010

The advantage of Constructor Initialization List in C++

Definition

Initialization List is another or a better approach for initializing the member variables (and base class objects) of a class upon construction of an instance of it's own.

Things to know about Initialization List

Initialization List is used to initialize both user defined data types (like embedded object of a class) and also primitive/built-in data types (like int, char).

Initialization List can appear irrespective of the place the constructor is defined.

Initializing the member variables in the Initialization List is better than initializing them inside the body of the constructor of the class.

Data members are initialized in the order they are declared, regardless of the order of their initialization.

It is mandatory to initialize Reference Data Member in an Initialization List because it can not exist without being initialized.

It is mandatory to initialize Constant Data Member in an Initialization List otherwise it would be constrcuted with some junk values and we cannot initialize it later anywhere else.

It is mandatory to construct and initialize, embedded class objects/base class objects in case of inheritance, in an Initialization List, if they do not themselves have a zero-argument/default constructor provided.
*************************************************************************************
Initializing the member variables in the Initialization List is better than initializing them inside the body of the constructor of the class.

There are two steps that takes place when Member Objects of a class are initialized inside the body of a constructor.

1. Member Objects are allocated a memry/constructed and are given default values by the time when the control enters body of the constructor.

2. Later on the actual initialization happens inside the body of the constructor i.e. user written initilization code that gets called.

Here there's an unnecessary first step where the member objects of a class gets constructed and are given a default value. An initialization list avoids this step and can make your code execute faster as a result.

Data members are initialized in the order they are declared, regardless of the order of their initialization.

It is important to know that the order of initializing the member variables in the Initialization List must match the order of their declarations inside the class. The reason is that the compiler automatically transforms the Initialization List so that it coincides with the order of the declaration of class members inside the class.
*************************************************************************************

In any constructor that initializes member objects, it can pay big dividends to set the objects using an initialization list rather than within the constructor itself. Why? Class member variables are automatically constructed using their default constructor prior to entry within the class constructor itself. You can override this behavior by specifying a different member constructor (usually a copy constructor) in the initialization list. Multiple initializations are separated with commas (not shown here).

template class CtorInit
{
T m_Value;
public:

// no list
CtorInit(const T& t) // m_Value default ctor called here automatically
{
m_Value = t; // m_Value assignment operator called
}

// with list
CtorInit(const T& t) : m_Value(t) { } // m_Value copy ctor called
};

*************************************************************************************

How to Initialize an Array in the C++ class

There are various ways in which you can initialize you array in the class
*************************************************************************
Method 1
*************
class A
{
int a[2];

public:
A();

};
A::A()
{
a[0]=1;
a[1]=2;
}
*************************************************************************************
You can also declare a static array and initilazes it's value outside the class scope

Method 2
*************

class A
{
static int a[2];
static const int arr[2];

public:
A(){}

};

int A::a[2] = {0, 1};
const int A::arr[2]={1,2};
*************************************************************************************
Note:

If you want to declare any const array in you class so you have to make it static const because const variables and arrays should be initialized at the time of declaring it.As we know that we cannot initialize arrays in initialization list so we cannot do it so we have to make the array static.

Initializing Array in the Constructor Initialization List

I have declared an int Array in my class and tries to initialize it through Constructor Initialization list but found error in doing so because this is not allowed in C++.

*********************************************************************************
I have written the following code.
*********************************************************************************
class A
{
private:
int Arr[3];

public:
A():Arr[0](1),Arr[1](2),Arr[2](3){}//produces error

}
*********************************************************************************
First we will discuss the behaviour of Array in C++
Whenever you declared an array lets say int Arr[3]; it will call the default constructor against each index like this...

Arr[0] //calls default constructor
Arr[1] //calls default constructor
Arr[2] //calls default constructor


if we have size N then it will call its default constructor N times.
*********************************************************************************
The above code produces error because whenever you declared an array you should initilize it also like this...

int Arr[]={1,2,3} //OK
int Arr1[3];
Arr[]={1,2,3};//Error


what we are doing is declaring and initializing it separately which is wrong.

Conclusion:
C++ does not support initialization of Arrays in the Constructor Initialization List because that is both syntactically and logically incorrect.If you have N size of items in you array you will never initiliaze it in Constructor Initialization List.

Tuesday, February 9, 2010

More MAGIC of SPRINTF

I was making a program in which i have to convert the following input into HEX Format

Input=01234567 (i.e; any number in between 0 and 9)
I have to covert these numbers into HEX like this

Output=3031323334353637

First I had made a logic which is as follows,

#define MAX_STRING_LENGTH 256

char input[MAX_STRING_LENGTH]; input array has the input like 012345...
memset (input, 0, MAX_STRING_LENGTH);

char output[MAX_STRING_LENGTH]; output array has the output like 30313233..
memset (output, 0, MAX_STRING_LENGTH);

NOTE : <> means less than
Method 1:

for int i=0,j=0;i <>LengthOf(input);i++,j+=2
{
output[j]='3';
output[j+1]=input[i];
}

Method 2:

for(int i=0,j=0;i<>LengthOf(input);i++,j+=2)
sprintf(output+strlen(output),"%c%c",'3',input[i]);


The difference betweent the two methods is that method 2 uses sprintf() function to perform the two operations at the same time whereas method 1 takes two operations to complete it.

In method 2,it is writing two characters at once means at the backend it first writes

output[0]='3';
output[1]=input[i];

we can write any format as we like by changing the second parameter format of sprintf()

References:
http://docs.roxen.com/pike/7.0/tutorial/strings/sprintf.xml
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
http://www.rohitab.com/discuss/index.php?showtopic=11505

The MAGIC of SPRINTF

sprintf()

Syntax:

#include
int sprintf( char *buffer, const char *format, ... );



Description:
The sprintf() function is just like |printf()|, except that the output is sent to buffer. The return value is the number of characters written.

Example:

char string[50];
int file_number = 0;

sprintf( string, "file.%d", file_number );
file_number++;
output_file = fopen( string, "w" );
//*****************************************************************************//

Wednesday, January 13, 2010

How to use memset function??

The memset() Function

To set all the bytes in a block of memory to a particular value, use memset(). The function prototype is

void * memset(void *dest, int c, size_t count);

The argument dest points to the block of memory. c is the value to set, and count is the number of bytes, starting at dest, to be set. Note that while c is a type int, it is treated as a type char. In other words, only the low-order byte is used, and you can specify values of c only in the range 0 through 255.

Example
/* memset example */
#include
#include

int main ()
{
char str[] = "almost every programmer should know memset!";
memset (str,'-',6);
puts (str);
return 0;
}



Output:


------ every programmer should know memset!

Wednesday, December 23, 2009

Introduction to the role of Server and Client

About Servers and Clients

There are two distinct types of socket network applications:
Server and Client.

Servers and Clients have different behaviors; therefore, the process of creating them is different. What follows is the general model for creating a streaming TCP/IP Server and Client.


Server


1. Initialize Winsock.
2. Create a socket.
3. Bind the socket.
4. Listen on the socket for a client.
5. Accept a connection from a client.
6. Receive and send data.
7. Disconnect.


Client


1. Initialize Winsock.
2. Create a socket.
3. Connect to the server.
4. Send and receive data.
5. Disconnect.

Note Some of the steps are the same for a client and a server. These steps are implemented almost exactly alike. Some of the steps in this guide will be specific to the type of application being created.