Monday, 25 August 2014

Why stack and heap both are necessary?

Both has its unique features. Stack is more efficient for allocating and deallocating the memory. Then you may ask whats the need for the heap.

Although heap is slower in allocation and deallocation of memory, heap as a unique feature that it can be allocated and deallocated at any place the programmer wish.

Consier the following example:

int *a=new int(10000000);
float *b=new  float(1);

In the above case, either a or b can be deallocated first based on the need. But in the case of stack it will deallocate in orderly fashion


Where the memory for pointer variable will be allocated?

It is allocated on the stack. (Remember it is Pointer variable not the dynamic memory allocated)



Thursday, 14 August 2014

#include<cstdio>

void callme(int callme)
{
    printf("\n I was called!");
}

class test
{
    int main;
   
};


int main()
{
    int main;
    // float main; Gives error
    //test main; Gives error
   
    callme(4);
    return 0;
}

Do you think it gives error?

No it will not give compile error.

Do you think C++ is mad to allow like this?

Not so, The above statement is allowed because  function name main is in different scope and integer main is in different scope. But The following program gives the error

int main; // main occured 1st time in scope
int main() // Oh! main occured 2nd time in scope. Error
{
    int main;
    // float main; Gives error
    //test main; Gives error
   
    callme(4);
    return 0;
}

Here the 1st main (integer) and second main(function name) both in same scope. so it will give the error.

To better understood watch the following program.


#include<cstdio>


int main()
{
    int my_var;
    {
        int my_var;
        {
            int my_var;
            {
                int my_var;
            }
        }
    }
    printf("Hurray! No Compiler error")    ;
    return 0;
}

Can we create a object of same type for the class?


#include<stdio.h>


class fruit
{
    // fruit f; Not possible
    static fruit f; // Not part of class objects memory
    fruit *fp;
    fruit &fr;
}

int main()
{
    fruit apple;
}





No is is not possible at all.

Why class cannot data member object of self type?


The class cannot have the data member of self type. Because the size of the data member object was not known at the compile time. say suppose one int and self type in the class

32-bit machine

class fruit
{
    int a;// 4 bytes
    fruit f;// 4+ sizeof(fruit);
}

Now the size of the fruit object declared inside the class can be found using the following formula

4+sizeof(fruit)

What will be the result of sizeof(fruit) value?

It is combination of a int variable and fruit object f.

This loops continuosly as mentioned below

4 + sizeof( 4 + sizeof( 4+ sizeof(4 + sizeof(..................))))

 

So why pointer and reference objects are allowed?


It is allowed because its size is known. By defauly pointer size is common to all kinds of classes. So we need to worry and stack allocates the memory without any trouble.




Wednesday, 13 August 2014

What will be the output of following program?

#include<cstdio>

class empty
{
};

class subclass : public empty
{
}


int main()
{
    empty e;
    printf("Size of object created for empty class :: %ld",sizeof(e));
}


Answer


 Size of object created for empty class :: 1

Reason



Why size is not zero but 1?

Size is not zero. It is 1 by default. It is mandtory defined by standard to
keep the size of the object of empty class as 1. This is because to differentiate
the two differnt object created for that class. They will differentiate the two different classes with the memory address.


Size of derived while inherting the empty class

#include<cstdio>

class empty
{
};

class subclass : public empty
{

};        


int main()
{
    empty e;
    printf("Size of object created for empty class :: %ld",sizeof(e));
    subclass s;
    printf("\nSize of object created for derived class inherited to empty class:: %ld",sizeof(s));
   
}

Answer:


Size of object created for empty class :: 1
Size of object created for derived class inherited to empty class ::1

Reason:


Why size of object with inherited class also 1 instead of 2?

Actually nothing will be stored in the empty classes. The 1 byte is allocated to uniquely refer the object in the program. So 1 byte is required. There will be one memory address for the one byte and we can uniquely identify the object in the program.


Thanks to http://www.geeksforgeeks.org/ for intiating this idea

Thursday, 7 August 2014


#include<iostream>
using namespace std;

class node
{
 
 public:
  int value;
  node *next;
 
  node()
  {
   next =NULL;
   value = 0; 
  }
  
};

class List 
{
 public:
 
  List()
  {
   head = NULL;
  }
  
  node *head;
  
  bool insert_node(node *p_head,int p_value)
  {
  
   node *temp= new node();
   temp->next = NULL;
   temp->value = p_value;
   
   if(! p_head)
   {
    head = temp;
    return true;
   }
   
   while(p_head->next != NULL)
   {
    p_head = p_head->next;
   }
   
   p_head->next = temp;
   return true;
  }
  
  bool deduct_loop(node *p_head)
  {
   node *slow=NULL,*fast=NULL;
   if(p_head)
    slow = p_head->next;
   int a;
   a=5;
   if(p_head->next)
    fast = p_head->next->next;

 /* Slow(Tortoise) will move one step at each loop and fast(Hare) moves two steps at each loop */

 while(slow && fast && fast->next)
   {


// Hare captured the tortoise. Always hare only capture the tortoise

 if(slow == fast) 
    {
     cout<<"\n Loop deducted!\n ";
     return true;
    }
    slow=slow->next; // Move one step
    fast=fast->next->next; // Move two step
   }


 // Reached End of Loop because Fast(Hare) is null 


// If no loop then end of loop is always reached by hare 


 cout<<"\n Good Job! No Loop deducted!";
   return false;
  }
};


int main()
{

 List list;
 
 list.insert_node(list.head ,10);
 list.insert_node(list.head ,20);
 list.insert_node(list.head ,30);
 list.insert_node(list.head ,60);
 list.insert_node(list.head ,40);
 
 cout<<"\n Demonstrating Linked list without loop";
 
 list.deduct_loop(list.head);
 
 cout<<"\n Demonstrating Linked list with loop";
 (list.head)->next->next->next = (list.head)->next;
 
 list.deduct_loop(list.head);
 
 return 0;
}


Friday, 11 July 2014

Malloc

  1.  Malloc will be defined in the stdlib.h or malloc.h depending on the operating system we  use.
  2. Malloc does not reset the bits to zero
  3. malloc returns null if memory cannot be allocated
Calloc

  1. Calloc allocates the memory based on the two parameter. second parameter says how much memory should be allocated and first how many memory like that to be created,
  2. calloc(count,sizeof(individual))
  3. c in calloc stands for clear or count
  4. Calloc reset all the bits to zero
  5. Calloc returns null if memory cannot be allocatedEE
Realloc

  1. If developer wish to increase or decrease the size, one can use the realloc function
  2. The content of the previous value will be left unchanged
  3. If ptr is null then reealloc function will work as same of malloc function.
  4. reallloc can create the memory at different place and copy the content.

Friday, 4 July 2014

still intializing the variable using the equal sign.

 C++03 standard introduced the new way of intializing the variable.

You can use the paranthesis to initialize the variable now.

#include<iostream>
int main()
{
   
    int n(88);
    std::cout<<n;
   
    double d(512.5415);
    std::cout<<d;
   
   
    return 0;
}


In c++11 standard you can use curly braces to initialize the variable.


#include<iostream>
int main()
{
   
    int n{88};
    std::cout<<n;
   
    double d{512.5415};
    std::cout<<d;
   
   
    return 0;
}

Tuesday, 1 July 2014

array type has incomplete element type

PROGRAM

#include<stdio.h>

int main()
{

    int arr[][]= { {1,2}, {3,4}} ;

    printf(":: %d :: %d ",arr[0][1],arr[1][1]);


    return 0;
}





ERROR STATEMENT GCC

error: array type has incomplete element type


EXPLANATION:

The size of the two dimensional array cannot be initialized when initializing the value for the two dimensional array.




For eg:

int arr[]={1,2,3,4} // valid

int arr[][]={{15,3},{62,5}}; // Not valid in c and c++
int arr[][10]={{1,3},{852,5}}; // valid in c and c++


In more general, the multi dimensonal array size should be mentioned even though we are intialzing the array at the time of declaration.


But the 1st dimension can be left uninitialized.

 

Wednesday, 25 June 2014

Hope you all remember the idioms  like "Passed out with flying colours, At your finger tips "used in our school days.

Its time to learn the program idioms.





"Gracefull exit" is an program idiom used by the programmers.

When your program, crashes due to some unexpected thing. What will happen to 

1. the things which reside in the program memory.
2. Sockets connections 
3. Cursors opened in the database


All the information in memory will be lost and some locks created by the program will remain. This will cause some unexpected things.

What is grace full exit?



The process of handling the errors and getting required information when the program shutdown unexpectly is called grace full exit.

The program will gather all the required information when the program shutdown.



Is unexpected shut down is grace full exit


No, it not only the unexpected shut down. Consider the server, which will continuously serves for the client request. In such situation To shutdown the server you will force application to bring down the server. At such situations it is necessary to  collect the some information from the server which is running.

The collection of such information is also an grace full exit.





 

Sunday, 18 May 2014

#include<iostream>

int main()
{
   using namespace std;

   unsigned int a=0;

   int aa=-10;
   a=(unsigned int)aa;
   cout<<"\nUNSIGNED COUT"<<a;
   printf("\nUNSIGNED PRINTF\n  :: %d ",a  );

   return 0;

}



OUTPUT
========================================


UNSIGNED COUT4294967286
UNSIGNED PRINTF -10
#include<iostream>
#include <stdlib.h>
int main()
{
   using namespace std;

   int i=0,item_read=0,j=0;


   while(true)
   {
      item_read=0;
      item_read=scanf("%d%d",&i,&j);
      

      if(item_read == 2)
      {
         printf(" Items read :: %d",item_read );
      }
      else
      {
         printf("\nError in reading!!!!!!");
         getchar();
         continue;
      }

   }


   return 0;
}



OUTPUT
========================================

11

2
 Items read :: 2










#include<iostream>

class class_test
{
   public:
      static int a;

};

int class_test::a; // Declare before use
int main()
{
   using namespace std;
 //   int class_test::a; Cannot declare here
   class_test::a=20;
   printf("\n class_test::a :: %d ", class_test::a );
  
   return 0;
}



OUTPUT
========================================

class_test::a :: 20

Tuesday, 29 April 2014

Have you ever tried to find the remainder of the two floating point numbers.


Are u going to use the modulus operator?

No we cannot achieve this using the modulus operator?


Let us try with modulus operator? Let see what happens

    float f=1.23%1.5;


The following error will occur.

     error: invalid operands to binary % (have ‘double’ and ‘double’)

So whats the idea?

math.h library provides the solution for it.

    fmod(double dividend,double divisor);

This will returns the remainder of two floating point numbers.

SAMPLE PROGRAM:

 

    #include"stdio.h"

    int main()
    {
            printf("%d", fmod(1.25/1.5));
            return 0;
    }

OUTPUT:

1.25000

If you pass the divisor as 0, the overflow will occur and fmod returns the zero.

Compilation hint:

gcc test.c -lm

Here the lm is the library for the math file.

Thursday, 27 March 2014


C provides the standard library to calculate the system time. In c you need to include the header file time.h and in c++ you need to include <ctype>

DATE_TYPE:

time_t is the data type name used for storing the epoch time.  The typedef of time_t is varies depend upon the platform. It is usually a long int or float type. 

Note on epoch time:

The epoch time is nothing but the number of seconds since 1 JAN 1970. The 1 Jan 1970 is UTC time. This time is also called unix time or posix time.

struct tm:

struct tm {               int tm_sec;         /* seconds */               int tm_min;         /* minutes */               int tm_hour;        /* hours */               int tm_mday;        /* day of the month */               int tm_mon;         /* month start with 0  */               int tm_year;        /* year since 1900*/               int tm_wday;        /* day of the week */               int tm_yday;        /* day in the year */               int tm_isdst;       /* daylight saving time */           };


FIND THE TIME DIFFERENCE:

double difftime(time_t time1, time_t time2);
This returns the difference between the two times in double format.

time function:
time_t time(time_t *epoch_time)
This function actually returns the number of seconds till JAN 1 1970. Note that the return value of the time function is also an time_t. If argument is not a null pointer then the value stored in the timer and return value will be same. If time function fails to fetch the calendar time then it returns null.

timer=time(NULL);

The argument can be passed as NULL. Even If passed as NULL, the return value will be time_t.

localtime function:

This localtime converts the epoch time to readable format. The local time returns the struct tm.

time_struct = localtime(&current_time);

mktime function:

time_t mktime (struct tm * time_struct);

This does the reverse process of the localtime. It returns the epoch time based on time struct. But make sure that the year should be subtracted from 1900 and month by 1 before converting  to epoch time when tm struct was filled manually.

printf("\n mk_time to get epoch time again  :: %d ",    mktime(time_struct));

asctime function:

It converts the time struct to human readable format.

char* asctime (const struct tm * time_struct);

The snippet is
printf("\n asctime :: %s ", asctime(time_struct) );

strftime:

This function is used to format the date according to our needs and stores in a buffer 

 size_t strftime (char* formatted_string, size_t maxsize, const char* format,const struct tm* time_struct );

Choose the list of format specifers from here
http://www.cplusplus.com/reference/ctime/strftime/

some basic format specifiers are
Format Meaning
%b Month name in abbreviation (Aug)
%d day of month (01-31) Zero padded for single digit
%e Day of month( 1-31) Space padded for single digit
%m month as decimal number(01-12)
%M minutes (00-59)
%y Year last two digits (92)
%Y Year last four digits (1992)
%H Hour in 24 Hour format (00-23)
%S Seconds(0-61)

Simple formatted time is
printf("\n  formatted_time :: %s ",  formatted_time   );
gmtime:

This function is used to compute the Greenwich median time
struct tm * gmtime (const time_t * timer);
ctime:
This is similar to the asctime
char* ctime (const time_t * timer);

Clock function:

This is used to calculate the cpu time
clock_t clock ();
The return type of the clock function is the clock_t. which is the basic arithmetic type typedefed to clock_t.
The return value is the number of clock ticks that elapsed till the epoch time.

So to calculate the clock time of program execution take the difference of two clock time executed at start and end of the program

It also has the inbuilt macro CLOCKS_PER_SEC to calculate the cpu time in terms of seconds.

Sample  Program:
#include<iostream>#include<cstdio>#include<ctime> // In c it is <time.h>
int main(){   using namespace std;
   time_t last_connect_time,current_time;   struct tm *time_struct;   char formatted_time[25];
   time(&last_connect_time);   sleep(1);   current_time=time(0); // This is similar to time(&current_time)   printf("\n DIFFERENCE TIME IN SECONDS  :: %f ", difftime(current_time,last_connect_time) );
   printf("\n Epoch time or unix time     :: %ld ",         current_time );
   time_struct = localtime(&current_time);   printf("\n CURRENT YEAR :: %d ",  (time_struct->tm_year+1900)     );   printf("\n CURRENT MON  :: %d ",  (time_struct->tm_mon+1)     );   printf("\n CURRENT DAY  :: %d ",  time_struct->tm_mday     );   printf("\n CURRENT HOUR :: %d ",  time_struct->tm_hour     );   printf("\n CURRENT MIN  :: %d ",  time_struct->tm_min     );   printf("\n CURRENT SEC  :: %d ",  time_struct->tm_sec     );
   printf("\n mk_time to get epoch time again  :: %ld ",    mktime(time_struct) );
   printf("\n asctime       :: %s ",     asctime(time_struct)     );   strftime(formatted_time,sizeof(formatted_time),"%d-%b-%y",time_struct);   printf("\n formatted_time:: %s ", formatted_time );

   return 0;}


Thursday, 13 March 2014



Fill is a template function used to initialize array or vectors using the some value. You should specify the starting pointer , number of elements to be reseted and value to be reseted.

Fill is the standard c++ function comes under the namespace std.
You can use fill to fill the array from intermediate.

SYNTAX:
void fill(type *start,type *end,const int reset_value);
SAMPLE PROGRAM:

#include<iostream>

int main()
{
   using namespace std;

   char arr[]="123456";
   printf("\n     arr   :: %s ",    arr      );
   fill(arr,arr+5,'a');
   printf("\n     arr   :: %s ",    arr      );

   return 0;
}

LIMITATIONS ON FILL FUNCTION:

  • you can reset the value in sequence only
  • This is similar to for loop internally
  • use of  memset is efficient when compare to fill but memset works on bytes level.

PROGRAMMING USAGE:
  • used for filling some range of value in the array
  • used for initializing array and vector

Monday, 3 March 2014


Before saying “what is local host?”, You should know about what is host first of all.
Host or node is nothing but a point in a network. Yes there is relation between the host and local host.

Here the Local host is nothing but that refers to the same node or host.

In other words,
local host is the host name(default host name) given to the ipaddress 127.*.*.*. series. 
All the packets which is sent to 127 series will be looped back to your host.

127 is the last series in the class a network.

Consider you were sending the packet to 127.0.0.1 nothing but the localhost, now the packet you send will be received by yourself. 




MECHANISM BEHIND LOCALHOST:

LOOPBACK is the interface that lies behind the local host mechanism.

what is loop back interface?
one of the main objective of networking is process of   sending and receiving the packet between the hosts.

In LOOPBACK the packets you were sending will not be delivered to your neighbor hosts. It will just deliver to your own machine. yes it like a throwing a ball on a wall infront of you. It will just come back to you. 

NEED FOR LOCALHOST:

If your server and client are at same station(computer) you can use the localhost.
Localhost never enters the network communication. It will be looped back by your system itself.

CAN WE USE LOCAL HOST WITHOUT NETWORK?

Yes you can very well use it. 

what you will do for determining the network connection between the two hosts. Probably you will type just ping followed by ipaddress. Just check it for local host like “ping 127.0.0.1”. Packets will be received on running this command and shows that network connection is available for loopback.
ping 127.0.0.1

Wednesday, 26 February 2014




Undefined behavior is nothing but  we cannot deduct how a application will react to some situation. Code will work fine without any semantic errors. But the output of the code was unpredictable.

C and C++ are most appropriate examples of such behavior.

For instance. If you declare a variable in c or c++, then you can use that variable without initializing it. Code will work fine for that situation. But the output of the code was unpredictable. It vary time to time. This behavior is called undefined behavior

HOW TO OVERCOME UNDEFINED BEHAVIOUR IN PROGRAMMING:
It is in the hands of the programmer to overcome the undefined behavior in programming.
There are also some tools available like valgrind,gdb  for pointing out these issues. Then always compile with –Wall (if your compiler is gcc) to overcome some of this issues.


WHY UNDEFINED BEHAVIOR:
The undefined behavior is allowed mainly to increase the efficiency and performance.
For eg consider the order of evaluation of function parameters.  some architecture will be fast when reading from left to right and vice versa.

DIFFERENCE BETWEEN UNSPECIFIED AND UNDEFINED BEHAVIOUR:
The undefined behavior and unspecified behavior both are different.
unspecified behavior is something where the implementation is undefined but it should conforms to standard. For eg evaluation of function parameters. Here the order of evaluation of function parameter is unspecified. It is up to the implementation.

Undefined behavior is something where we cannot predict the results. Here although it conforms to standards, here the result are unpredictable.
UNDEFINED BEHAVIOUR IN C AND C++:
1. USING THE VARIABLE WITHOUT INITIALIZATION:

when you use a variable without initializing then it leads to a undefined behavior. Because it use the garbage value. so its result is unpredictable at all time.

int a,b;b=a+10; // garbage value to b

2. FUNCTION WITHOUT A  RETURN STATEMENT:
As per semantics, the compiler will allow without return statement even if the return type of the function is other than void say int,float,double etc., But this will result in unpredictable results always.
int myfunction(){ // No return statement}int main(){ int a=myfunction();
}


3. VARIABLE SIZE OVERFLOW:

When the variable size overflows  then it will result in unpredictable results. For eg size of MAX_INT  is 65535. Then the following code will result in overflow. Here the if value of N is greater than the MAX_INT, the value of i never fails in the condition i<N because after variable i reaching the limit, it starts to count from 0 (INT_MIN). So the loop never ends.
for(i=0;i<N;i++){//Loop runs infinite times if N is greater than MAX_INT}

4. DEREFERENCING A DANGLING POINTER

When you free a memory after malloc. The memory will get freed. But the pointer will point to the same location even after the freeing process. Since the pointer refers to the freed memory. the pointer is called as dangling pointer. When you dereference a dangling pointer you will get the unpredictable results always.
char *p=(char *)malloc(sizeof(char)*5);
free(p); // Here memory deallocated but p points to same location. So p is a dangling pointer
*p=*p+1; //Unpredictable results
5. DEREFERENCING THE WILD POINTER:

The wild pointer is nothing but the uninitialized pointer. When you use a uninitialized pointer then it will return some garbage value
int *p;*p=*p+1; // undefined behaviour
6. RETURNING A ADDRESS OF LOCAL VARIABLE

When you return the address of the local variable, then it is also an undefined behavior.
int callme(){int a;return &a; // Scope of dies here. No use of passing a’s address}

7. CHANGING THE CONST CHAR POINTER
When you attempt to change the const char pointer then the result will be unpredictable.

char *p=”HELLO”;p[1]=’S’; // Lead to segmentation fault

in above snippet, the HELLO is string literal stored in read only memory. Here we are attempting to change the read only memory. Code works without any compilation error. But the segmentation fault error will occur.

Saturday, 22 February 2014

Context is used to connect two or more databases and it allows to switch between them in run time.


CREATING CONTEXT:

Context is created using the pseudo column sql_cursor.


sql_cursor mycursor;

The above declaration should be done inside the declare section of pro c/c++.


ALLOCATE THE CONTEXT:

The context should be allocated before they were used in the program.


EXEC SQL CONTEXT ALLOCATE :mycursor;

Note that for cursor allocation the same above statement is used but the clause context is removed.


USE THE CONTEXT:

We can switch between the context by using the following declaration.
The use statement should come before connecting to the database. Allocate is much similar to declaration.  


EXEC SQL CONTEXT USE :my_cusor;


DEFAULT IN CONTEXT:

You can swith to the default cursor by the following statement.
EXEC SQL CONTEXT USE DEFAULT;
The default is the keyword no semicolon comes before that.


SAMPLE PROGRAM



 #include"stdio.h"
Exec sql include sqlca;
int  main()
{
   exec sql begin declare section;
   char *usr1="usr1/usr1pwd@servicename1";
   char *usr2="usr2/usr2pwd@servicename2";
   char *usr3="usr2/usr2pwd@servicename3";
   sql_context usrcontext1;
   sql_context usrcontext2;
   int avg_mark;
   exec sql end declare section;
   exec sql whenever sqlerror go to sqlerr;

   // Connecting to default context

   EXEC SQL CONNECT :usr1;

   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   //allocating and connecting to usrcontext1

   EXEC SQL CONTEXT ALLOCATE  :usrcontext1;
   EXEC SQL CONTEXT USE :usrcontext1;
   EXEC SQL CONNECT :usr2;


   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);


   //allocating and connecting to usrcontext2


   EXEC SQL CONTEXT ALLOCATE  :usrcontext2;
   EXEC SQL CONTEXT USE :usrcontext2;
   EXEC SQL CONNECT :usr2;


   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   // Now i am connecting to default context database

   EXEC SQL CONTEXT USE DEFAULT;
   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   // Now i am connecting to usrcontext2  database

   EXEC SQL CONTEXT USE :usrcontext2;
   exec sql select AVG_MAR into :avg_mark from MARK_LIST where STUD_ID LIKE '121';
   printf("\n Avg Mark at connected database: %d",avg_mark);

   //By this way you can connect mutiple database and you can swith between them

   return 0;

sqlerr:
   printf("\nError in DB \n");

   return 0;
}


OUTPUT:

Avg Mark at connected database: 85.55
Avg Mark at connected database: 51.22
Avg Mark at connected database: 90.15
Avg Mark at connected database: 85.55
Avg Mark at connected database: 90.15


In above output note that 1st and 4th  line avg was same. This indicates that are connected to same database schema.

Monday, 17 February 2014


Apart from programming, template is one, which just defines the outline. Consider the leave letter template, which does not contain much information. As a template it contains only from address column but it does not have a from address. similarly it has a body section but it does not have for what purpose the leave is taken.
In c++, templates are much more similar to that. Here, in class template only the class name will be given while declaring. But which datatype the class uses will not be mentioned. This is more generic way of programming.
Then you may ask why there is need for template class?
Here the class does a same functionality for all datatypes. If template class was not there then you have to define the multiple class for each datatype that the class uses. But using templates we are creating only one class.

Real time example:

Consider the Arithemetic operation class. The datatype for the Arithemetic operation can be int, float, double. Inorder to define the multiple class we can just create the single template class and we can make specific whenever we are needed.

Syntax:

template <class type1> class template_class_name;
Eg:
template <class type1> class arithmetic_oper;

In above syntax, the template is keyword just to indicate the class is of type template. Then another new thing is <> brackets. while instantiation, the datatypes that are going to be used are mentioned there. In above we can allowed to instantiate using one type but we can give many as <class type1,class type2>.

DEFINING THE TEMPLATE CLASS:

This is just as normal class definition. In normal class definition you will be using the datatype as int. float etc for declaring the variable. But here you will be using the typename defined inside the angle brackets.
here type1 is identifier. This type1 can be int,float,double etc., 

This is decided while creation of object for the class.

template <class type1>class arithmetic_oper
{
   public:
      type1 variable_name;
     int fixed_type_int;
};


DIFFERENCE BETWEEN CLASS AND TYPENAME IN TEMPLATE:
There is no major technical difference between the class and typename. we can use them interchangeably. But at one rare case it is different. Need to explore that.


CREATING OBJECT FOR TEMPLATE CLASS:

arithmetic_oper <int> int_operation;

Here the arithmetic_oper is template class name. Here I want to make the class to use the int variable. so I have used int inside the angle brackets. I cannot give more than one type here. If I want to give more than one type then I need to declare the template class as <class type1,class type2>

CREATING TEMPLATE FUNCTION INSIDE THE  TEMPLATE CLASS:

Declartion of function template with new type inside the class template goes like this

template <class F_Type1> F_Type1  add(F_Type1,F_Type1);

Here the new type F_Type1 is created .
And the definition of template function goes like this
template <class c_Type1>
template <class type1>
type1 arithmetic_oper<c_Type1> ::  add(type1 a,type1 b)
{
   return a+b;
}
Here consider this, We have to specify the both templates such as class template c_Type1 and function template type1.

TYPE CASTING OF FUNCTION TEMPLATE:

consider the following snippet,
addition_value=(int)int_operation.add<int>(5.10,10);
Here the <int> represent the type casting to parameters. Here both parameter were different. If it was same, then compiler will auto deduct it. we are confusing the compiler in deducting the parameter type. So we explicitly indicate the compiler regarding parameter types. Then (int) is normal type casting. It stores the resultant value in to addition_value variable by typecasting to integer.

SAMPLE PROGRAM:

#include<iostream>
using namespace std;

template <class type1>
class arithmetic_oper; //declaring template

template <class type1>
class arithmetic_oper //defining template
{
   public:
      type1 variable_name; //Here we can change the datatype
      int fixed_type_int;  //cannot change the datatype

      // Using different type for function template
      template <class F_Type1> F_Type1  add(F_Type1,F_Type1);

      //Using same type as class for function template
      type1 sub(type1,type1);

};

template <class c_Type1>
template <class type1>
type1 arithmetic_oper<c_Type1> ::  add(type1 a,type1 b)
{
   return a+b;
}


template <class c_Type1>
c_Type1 arithmetic_oper<c_Type1> :: sub(c_Type1 a,c_Type1 b)
{
   return a-b;
}


int main()
{

   //Creating object as int using template
   arithmetic_oper <int> int_operation;
   int_operation.variable_name=10;
   printf("\nUsing a class as a integer :: %d ",int_operation.variable_name);
   
int addition_value=int_operation.add(5,10);
   printf("\nADDITION OF GIVEN VALUE IS %d",addition_value);
   addition_value=(int)int_operation.add<int>(5.10,10); // Type casting as int.
   printf("\nADDITION OF GIVEN VALUE IS with type casting %d",addition_value);


   //Creating object as double using template
   arithmetic_oper <double> double_operation;
   double sub_value=double_operation.sub(50.52,25.02);
   printf("\nSUBTRACTION OF GIVEN VALUE IS %f",sub_value);

   //Creating object as char using template
   arithmetic_oper <char> char_operation;
   char_operation.variable_name='A';
   printf("\nUsing a class as char type :: %c ",char_operation.variable_name);

   return 0;
}

OUTPUT:



Using a class as a integer :: 10
ADDITION OF GIVEN VALUE IS 15
ADDITION OF GIVEN VALUE IS with type casting 15
SUBTRACTION OF GIVEN VALUE IS 25.500000
Using a class as char type :: A 

Saturday, 8 February 2014

FILE EXTENSION
EXPANSION
compressed archive file
.rar
compressed archive file
.mpeg
motion picture expert group
.avi
audio and video interleave,developed by Microsoft in 1992
.art
clip art files
.bak
backup files
.cbl
cobol code
.doc
document file for word
.gif
graphics interchange format developed by compuserve for web
.htm
hypertext markup
.mp3
mpeg audio layer 3
.pdf
portable document file by adobe
.xml
extensible markup language
.3gp
 3rd generation partner ship project developed for 3g phones