Wednesday, August 1, 2012

Debugging Stuff/Memory Management in C++

Create class dynamically in Python
Metaclass
Python Class Attributes: An Overly Thorough Guide 

Class vs static methods in Python

stack implement as linked list
error: template declaration of ‘typedef’
undefined-reference-to-vtable-for-class

Memory Management
Gcov Coverage
Linux wiki

Error :undefined symbol: __gcov_merge_add (solution)

Configure

Lcov


Monday, June 4, 2012

Reference Material



C++
1. C++ FAQ
2. Test you skill in C++
3. Test you C skill
4. www.learncpp.com/
5. http://www.cppcoffe.blogspot.in/
6. http://www.geeksforgeeks.org/
7. http://www.tutorialspoint.com/cplusplus
8. Effective C++
9. http://c-pointer.blogspot.in/
10. http://www.careercup.com/



Data Structure
1.Data Structures ( a pseudocode approach with c++)
2.Data Structure and algorithm made easy
3.https://www.hackerrank.com/
4. http://www.geeksforgeeks.org/
5. googlegeeks group
6. http://www.careercup.com/
7. IIT delhi video lecture
8. Standford Data Structure Class
9. MIT open course Data Structure
10.Introduction to Algorithm
11.https://www.codechef.com/


DataBase
1.Crack IT interview DataBase
2. http://www.programmerinterview.com/index.php/database-sql/introduction/
3. http://sql-plsql.blogspot.in/2009/04/sql-interview-questions.html

4. http://www.orafaq.com/faq/what_are_the_difference_between_ddl_dml_and_dcl_commands
5. http://www.1keydata.com/sql/sql.html 
6. http://plsql-tutorial.com/index.htm

7. http://www.sqlcourse.com/index.html (online Compiler)
8. http://www.java2s.com/Tutorial/Oracle/CatalogOracle.htm 
9. http://apex.oracle.com/i/index.html

Unix Reference:
1.Crack IT interview with Unix DataBase
2.http://www.folkstalk.com/2011/11/top-unix-interview-questions-part-1.html 
3.www.thegeekstuff.com/2010/11/50-linux-commands/
4.http://faq.programmerworld.net/networking/unix-interview-questions-answers.html

5.linux.101hacks.com/linux-commands/cut-command-examples/
6.http://www.gointerviews.com/top-50-linux-interview-questions/ 
7.http://www.theunixschool.com/2012/04/linux-interview-questions-part-1.html  


Design Pattern:
1.Head & First Design Pattern (Book)
2.http://sourcemaking.com/design_patterns
3. http://www.javabeat.net/2009/02/design-patterns-interview-questions/
4. http://javarevisited.blogspot.in/2012/06/20-design-pattern-and-software-design.html

System Programming:
1.Galvin -Operating System Concept (7 Edition)
2. Programming with POSIX Threads

Verbal & Reasoning Reference :
1. Wren & Martin English Grammar Book
2. Word Power Made Easy
3.  Barron English Book

Good Link
1. Trick question  
2. Static object
3. Boost Pointer
4.  Thinking in c++ volume two
5.  C programming language
6. C++ notes
7. Encapsulation vs abstraction
8. Parashift Interview Question
9. Counter view
10.explicit constructor
11.scoped_ptr related link
12. Function Pointer
13. Call Back Function
14. call a C library from C++ code or   call a C++ library from C code?
15. Empty class
18. Vector inner implemention
19. Binary Tree
22. C++ Traits
23. FLEX Tutorial

Some Follow up url 

1.Git Hub
2. Hacker Rank
4.Open Source ProjectGoogle code jam(Good for beginner) 
8. Graph Theory implementation
9. Algo

Saturday, May 19, 2012

Tree_Program

 #include<iostream>  
 #define size 3  
 using namespace std;  
 class node  
 {  
  public:       
  int data;  
  node *left;  
  node *right;  
 };  
 class tree  
 {  
  public:  
  node *root;  
  tree();  
  void create_tree(int data);  
  void inorder_traverse(node *s);  
  void print_data();  
 };  
 tree::tree()  
 {  
      root=NULL;  
 }  
 void tree::create_tree(int data)  
 {  
   node *temp = new node;  
   temp->data = data;  
   temp->left =NULL;  
   temp->right =NULL;  
   if(root ==NULL)  
        root =temp;  
   else  
   {  
       node *p =root;  
       node *trail =NULL;  
      while(p!=NULL)  
       {   
         root=p;  
        if(p->data > data)  
         {  
             p =p->left;  
         }  
         else  
           {  
              p=p->right;  
           }  
       }  
       if(root->data > data)  
       {  
         root->left =temp;  
       }  
       else  
       {        
         root->right = temp;  
       }  
   }  
 }  
 void tree::inorder_traverse(node *s)  
 {   
    if(s)       
    {  
         inorder_traverse(s->left);  
         cout<<s->data<<"  ";  
         inorder_traverse(s->right);  
    }  
 }  
 void tree::print_data()  
 {  
      inorder_traverse(root);  
 }  
 int main()  
 {  
  int data;  
  tree t;  
  for(int i=0;i<3;i++)  
  {  
      cout<<"Enter data";  
       cin>>data;  
       t.create_tree(data);  
  }  
  cout<<"inorder: traverse :"<<endl;  
  t.print_data();  
  return 0;  
 }  
Create_tree with level_order_traversal
 #include<iostream>  
 using namespace std;  
 class node  
 {   
   public:       
   int data;  
   node *left;  
   node *right;  
 };  
 class tree  
 {  
   public:  
   node *root;  
   tree();  
   void create_tree(int data);  
   void print_tree();  
   void tree_level_order_traverse(node *root);  
 };  
 tree::tree()  
 {  
   root =NULL;  
 }  
 void tree::create_tree(int data)  
 {  
   node *temp = new node;  
   temp->data = data;  
   temp->left = NULL;  
   temp->right =NULL;  
   if(root==NULL)  
     root=temp;  
   else  
   {  
    node *p=root;  
    node *trail =NULL;  
    while(p!=NULL)  
    {  
      trail=p;  
       if(p->data > data)  
         p=p->left;  
      else  
         p=p->right;  
    }  
    if(trail->data > data)  
       trail->left = temp;  
    else  
       trail->right = temp;  
   }  
 }  
 void tree::tree_level_order_traverse(node *root)  
 {  
   node *data_store[10] = { (node*)0} ;  
   int size=0;  
   int follow_variable=0;  
   while(root)    
   {  
    cout<<root->data<<" :";  
    if(root->left)  
      data_store[size++]=root->left;  
    if(root->right)  
    data_store[size++]=root->right;  
     root=data_store[follow_variable++];  
   }  
 }  
 void tree::print_tree()  
 {  
      tree_level_order_traverse(root);  
 }  
 int main()  
 {  
   tree t;       
   for(int i=0;i<8;i++)  
       t.create_tree(i);  
   cout<<"create successful"<<endl;  
   t.print_tree();   
   return 0;  
 }  
Tree_header_file
 #include<iostream>  
 using namespace std;  
 class node  
 {  
   public:  
   int data;  
   node *left;  
   node *right;  
 }  
 class tree  
 {  
  public:  
  node *root;  
  tree();  
  void create_tree(int data);  
 };  
 tree::tree()  
 {  
  root =NULL;  
 }  
 void tree::create_tree(int data)  
 {  
      node *temp= new node;  
      temp->data = data;  
      temp->left =NULL;  
      temp->right =NULL;  
      node *p=root;  
      while(p!=NULL)  
      {  
       root =p;  
        if(p->data > data)  
          p=p->left;  
        else  
          p=p->right;  
      }  
      if(root->data > data)  
           root->left = temp;  
      else  
           root->right = temp;  
 }  

Find_Max_Element_without_Recursion

 template<class T>  
 int tree<T>::find_max_element(node *root)  
 {  
  node *queue[10]= {(node*)0};  
  node *p=root;  
  int data;  
  int size=0;  
  int follow_variable =0;  
  int max=0;  
  while(p!=NULL)  
  {  
   if(max < p->data)  
       max = p->data;         
   if(p->left)  
        queue[size++] = p->left;  
   if(p->right)  
        queue[size++] = p->right;  
    p = queue[follow_variable++];  
  }    
    cout<<"the max data :"<<max<<endl;  
  return max;  

Find_Max_Element_with_Recursion

 int tree<T>::find_max_element(node *root)  
 {  
  int root_value;  
  int left;  
  int right;  
  int max =0;  
  if(root!=NULL)  
  {  
    root_value = root->data;  
    left = find_max_element(root->left);  
    right = find_max_element(root->right);  
    if(right > left)  
         max=right;  
    else  
         max=left;  
  if(root_value > max)  
       max=root_value;  
  }  
  return max;  
Reverse_level_order_traverse
 void tree::reverse_level_order(node *root)  
 {  
   node *temp_storage[10]= {(node *)0};  
   int size =0;  
   int flow_variable =0;  
   while(root)  
   {  
    cout<<" "<<root->data;  
    if(root->right)  
    {  
          temp_storage[size++]=root->right;  
    }  
    if(root->left)  
    {  
         temp_storage[size++] = root->left;  
    }   
    root=temp_storage[flow_variable++];  
  }  
 }  

Thursday, April 14, 2011

C++ Program list 2

1. reverse string program
2. Find out the day of a given  date in particular year
3. Print Pascal Triangle
4. To remove same word from the string 
5. we need to find any particular string and replace with convert string
  
reverse string program

/*


* This file contain reverse string program

* */

#include<iostream>
using namespace std;

template<class T>
class str
{
public:
char *p;
str();
void reverse();
void show();
};

template<class T>
str<T>::str()
{
p=new char[20];
cout<<" enter the string"<<endl;
cin>>p;
}

template<class T>
void str<T>::reverse()
{
char temp;
int count=0;
while(p[count]!='\0')
count++;
for(int i=0;i<count/2;i++)
{
temp =p[count-i-1];
p[count-i-1]=p[i];
p[i]=temp;
}
}
template<class T>
void str<T>::show()
{
cout<<p;
}
int main()
{
str<char>s;
s.reverse();
s.show();
return 0;
}

Find out the day of a given  date in particular year
#include<iostream>

#include<string>
#define BASEYEAR 100

using namespace std;
template<class T>
class leap
{
public:
leap();
int leap_year(int year);
long today;
void get_day();
};
template<class T>
leap<T>::leap()
{
today =0;
}
template<class T>
int leap<T>::leap_year(int year)
{
if((year%4==0 && year%100!=0)
(year%400==0))
return 1;

else
return 0;
}

template<class T>
void leap<T>::get_day()
{
int date;
cout<<" Enter date"<<endl;
cin>>date;
int month;
cout<<" Enter month"<<endl;
cin>>month;
int year;
cout<<"Enter year"<<endl;
cin>>year;
string day[]={"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
int day_of_month[]= {31,28,31,30,31,30,31,31,30,31,30,30};

for(int i=BASEYEAR;i<year-1;i++)
{
if(leap_year(i))
today=today+366;
else
today=today+365;
}

if(leap_year(year))
day_of_month[1]=29;

for(int i=0;i<month-1;i++)
today =today+day_of_month[i];

today+=date;
cout<<"today--->"<<today<<endl;
int wday =today%7;

cout<<" The day is ---->"<<day[wday];
}

Print Pascal Triangle


* Print Pascal Triangle


*

* 1

* 1 1

* 1 2 1

* 1 3 3 1

*

* */

#include<iostream>
using namespace std;
int main()
{
int a[20];
a[0]=1;
int k;
for(int i=0;i<10;i++)
{
int y=0;
for(int j=10;j>=i;j--)
cout<<" ";

for(k=0;k<=i;k++)
{
int p=y+a[k];
y=a[k];
a[k]=p;
cout<<p<<" ";
}

a[k]=0;
cout<<endl;
}
return 0;
}

To remove same word from the string
 
#include<iostream>

using namespace std;

char* word(char *p)
{
char *filter =new char[20];
int count=0;
int i=0;
while(p[count]!='\0')
count++;

for(i=0;p[i]!='\0';i++)
{
for(int j=i+1;p[j]!='\0';j++)
{
if(p[i]==p[j])
{
p[j]=p[j+1];
i=0;
cout<<" inside if block"<<endl;
}
}
}
p[i]='\0';
return p;
}
int main()
{
char *w=new char[20];
cout<<"enter the word"<<endl;
cin>>w;
cout<<word(w);
return 0;
}

/*

* we need to find any particular string and replace with convert string
* Ex.
* hi ss
* abhishek --->ab(hi)shek----->abssshek
*
* */

#include<iostream>

using namespace std;
char *change(char *p,char *find,char *replace)
{
int find_length=0;
while(find[find_length]!='\0')
find_length++;

int replace_length=0;
while(replace[replace_length]!='\0')
replace_length++;

for(int i=0;p[i]!='\0';i++)
{
for(int j=0;p[j]!='\0';j++)
{
if(p[i]==p[j])
{
int k=i;
int j=0;
while(find[j]!='\0')
{
if(p[k++]!=find[j])
break;
j++;
}
if(j==find_length)
{
int re =0;
//if the replace length are same
if(find_length==replace_length)
{
while(replace[re]!='\0')
{
p[i++]=replace[re++];
cout<<p[i]<<endl;
cout<<i<<endl;
}
}
//if the replace lenth are less
if(find_length>replace_length)
{
while(replace[re]!='\0')
p[i++]=replace[re++];

while(p[i]!='\0')
{
p[i]=p[i+2];
i++;
}
}
}
}
}
}
return p;
}
int main()
{
char *p=new char[40];
cout<<"Enter the string"<<endl;
cin>>p;
char *find =new char[40];

cout<<" Enter the find string"<<endl;
cin>>find;
char *replace =new char[40];

cout<<"Enter the replace"<<endl;
cin>>replace;


cout<<" final string "<<change(p,find,replace)<<endl;
return 0;
}





 
 



int main()

{

leap<int> l;

l.get_day();



return 0;

}

Sunday, October 10, 2010

Inter Process communication

This is collectively notes  from diffirent internet material nd put some of my analysis with
diffirent topic.

The purpose of this article is to get the readers familiar with the different mechanisms that are available for communicating between two or more processes. This may also serve as a tutorial for the novice programmer. There might be several good tutorials on this subject

Introduction

Inter-Process Communication, which in short is known as IPC, deals mainly with the techniques and mechanisms that facilitate communication between processes. Now, why do we need special separate mechanisms or techniques for communicating between processes? Why isn't it possible to have information shared between two processes without using such special mechanisms?
Let us start from something primitive. Imagine you have two glasses completely filled with water. One glass contains hot water and the other contains cold water. What can you do to make the temperature of water in both the glasses equal? The simplest answer will be to mix the water from both the glasses in a glass with much bigger capacity. Once water is mixed, the temperature becomes equal after some time. If one can remember, this will be framed as a problem with some numerical data in a High-School Physics examination. If we go by principles, then the phenomenon here is conduction. If we go by our topic of IPC, then we can say that since the two glasses were full, we had to use another glass with a larger capacity to mix the contents in order to balance their heat energy.
Have you ever wondered about the communication medium used in telephones? What about the blood transporting system in the human body which communicates blood to different parts of the body? What about my fingers which are typing this document? My brain is doing so many things at a time. How is it directing one of my fingers to hit one key and some other finger to hit another key? How is it synchronizing the typing work that is done by both my hands? How is it also directing me to type the letters of a word that are actually coming to my mind?
Don't worry. I am not going to give a class in Biology. But it would be good if one can imagine a few more situations where we are using inter-process communication, though not necessarily in the human body or in a computer program.
So, where are we now? We know that some medium or other is required for communication between different processes. Similarly, when it comes to computer programs, we need some mechanism or medium for communication. Primarily, processes can use the available memory to communicate with each other. But then, the memory is completely managed by the operating system. A process will be allotted some part of the available memory for execution. Then each process will have its own unique user space. In no way will the memory allotted for one process overlap with the memory allotted for another process. Imagine what would happen otherwise!
So, now the question - how do different processes with unique address space communicate with each other? The operating system's kernel, which has access to all the memory available, will act as the communication channel. Similar to our earlier example, where the glass with hot water is one process address space, the glass with cold water is another, and the glass with the larger capacity is the kernel address space, so that we pour both hot water and cold water into the glass with larger capacity.
What next? There are different IPC mechanisms which come into use based on the different requirements. In terms of our water glasses, we can determine the specifics of both pouring the water into the larger glass and how it will be used after beign poured.

Basic IPC

OK, enough of glasses and water. The IPC mechanisms can be classified into the following categories as given below:
  1. pipes
  2. fifos
  3. shared memory
  4. mapped memory
  5. message queues
  6. sockets

Pipes

Pipes were evolved in the most primitive forms of the Unix operating system. They provide unidirectional flow of communication between processes within the same system. In other words, they are half-duplex, that is, data flows in only one direction. A pipe is created by invoking the pipe system call, which creates a pair of file descriptors. These descriptors point to a pipe inode and the file descriptors are returned through the filedes argument. In the file descriptor pair, filedes[0] is used for reading whereas filedes[1] is used for writing.
Let me explain a scenario where we can use the pipe system call: consider a keyboard-reader program which simply exits after any alpha-numeric character is pressed on the keyboard. We will create two processes; one of them will read characters from the keyboard, and the other will continuously check for alpha-numeric characters. Let us see how the filedes returned by pipe can be of use in this scenario: (Text version: kbdread-pipe.c.txt)
/***** KEYBOARD HIT PROGRAM *****/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>

int filedes[2];

void *read_char()
{
 char c;
 printf("Entering routine to read character.........\n");
 while(1) {
  /* Get a character in 'c' except '\n'. */
  c = getchar();
  if(c == '\n')
   c = getchar();
  write(filedes[1], &c, 1);
  if(isalnum(c)) {
   sleep(2);
   exit(1);
  }
 }
}

void *check_hit()
{
 char c;
 printf("Entering routine to check hit.........\n");
 while(1) {
  read(filedes[0], &c, 1);
  if(isalnum(c)) {
   printf("The key hit is %c\n", c);
   exit(1);
  } else {
   printf("key hit is %c\n", c);
  }
 }
}
  
int main()
{
 int i;
 pthread_t tid1, tid2;
 pipe(filedes);
 /* Create thread for reading characters. */
 i = pthread_create(&tid1, NULL, read_char, NULL); 
 
 
/* Create thread for checking hitting of any keyboard key. */
 i = pthread_create(&tid2, NULL, check_hit, NULL);
 if(i == 0) while(1);
 return 0;
}

What is mean of  pthread_create(&tid1, NULL, read_char, NULL);

Just FYI:
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,  void *(*start_routine)(void*), void *restrict arg);



Description
The pthread_create() function shall create a new thread, with attributes specified by attr
within a process. If attr is NULL, the default attributes shall be used.
If the attributes specified by attr are modified later,the thread's attributes shall not be affected.


Upon successful completion, pthread_create() shall store the ID of the created thread in the location referenced by thread.


The thread is created executing start_routine with arg as its sole argument.

If the start_routine returns, the effect shall be as if there was an implicit call to pthread_exit()  
using the return value of start_routine as the exit status.

Note that the thread in which main() was originally invoked differs from this.When it returns from main(), 
 the effect shall be as if there was an implicit call to exit() using the return value of main() as the exit status. 
The signal state of the new thread shall be initialized as follows:
The signal mask shall be inherited from the creating thread
The set of signals pending for the new thread shall be empty
The alternate stack shall not be inherited
The floating-point environment shall be inherited from the creating thread.

If pthread_create() fails, no new thread is created and the contents of the location referenced by thread are undefined

Save and compile the program as cc filename.c -lpthread. Run the program and check the results. Try hitting a different key every time.
The read_char function simply reads a character other than '\n' from the keyboard and writes it to filedes[1]. We have the thread check_hit, which continuously checks for the character in filedes[0]. If the character in filedes[0] is an alpha-numeric character, then the character is printed and the program terminates.
One major feature of pipe is that the data flowing through the communication medium is transient, that is, data once read from the read descriptor cannot be read again. Also, if we write data continuously into the write descriptor, then we will be able to read the data only in the order in which the data was written. One can experiment with that by doing successive writes or reads to the respective descriptors.
So, what happens when the pipe system call is invoked? A good look at the manual entry for pipe suggests that it creates a pair of file descriptors. This suggests that the kernel implements pipe within the file system. However, pipe does not actually exist as such - so when the call is made, the kernel allocates free inodes and creates a pair of file descriptors as well as the corresponding entries in the file table which the kernel uses. Hence, the kernel enables the user to use the normal file operations like read, write, etc., which the user does through the file descriptors. The kernel makes sure that one of the descriptors is for reading and another one if for writing.

FIFOs
FIFOs (first in, first out) are similar to the working of pipes. FIFOs also provide half-duplex flow of data just like pipes. The difference between fifos and pipes is that the former is identified in the file system with a name, while the latter is not. That is, fifos are named pipes.
Fifos are identified by an access point which is a file within the file system, whereas pipes are identified by an access point which is simply an allotted inode.

*inode
The inode (index node) is a fundamental concept in the Linux and UNIX filesystem. Each object in the filesystem is represented by an inode.
But what are the objects? Let us try to understand it in simple words.
 Each and every file under Linux (and UNIX) has following attributes:
  •  File type (executable, block special etc)
  • Permissions (read, write etc)
  • Owner
  • Group
  • File Size
  • File access, change and modification time (remember UNIX or Linux never stores file creation time, this is favorite question asked in UNIX/Linux sys admin job interview)
  • File deletion time
  • Number of links (soft/hard)
  • Access Control List (ACLs)
All the above information stored in an inode.
In short the inode identifies the file and its attributes (as above) . Each inode is identified by a unique inode number within the file system. Inode is also know as index number.

inode definition 

An inode is a data structure on a traditional Unix-style file system such as UFS or ext3. An inode stores basic information about a regular file, directory, or other file system object.

How do I see file inode number?

You can use ls -i command to see inode number of file
$ ls -i /etc/passwd
Sample Output
32820 /etc/passwd

You can also use stat command to find out inode number and its attribute:
$ stat /etc/passwdOutput:
 
File: `/etc/passwd'
  Size: 320347          Blocks: 640        IO Block: 4096   Regular File
Device: 6801h/26625d    Inode: 196570      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2010-10-16 10:49:12.000000000 -0700
Modify: 2010-10-16 10:43:27.000000000 -0700
Change: 2010-10-16 10:43:27.000000000 -0700 
 
Inode application Many commands used by system administrators in UNIX / Linux operating systems often give inode numbers to designate a file. Let us see he practical application of inode number. Type the following commands:
$ cd /tmp
$ touch \"la*
$ ls -l

Now try to remove file "la*
You can't, to remove files having created with control characters or characters which are unable to be input on a keyboard or special character such as ?, * ^ etc. You have to use inode number to remove file.
 
Difference between find & grep

Grep - grep search the pattern in the file

find -search for the file in the director

Another major difference between fifos and pipes is that fifos last throughout the life-cycle of the system, while pipes last only during the life-cycle of the process in which they were created. To make it more clear, fifos exist beyond the life of the process. Since they are identified by the file system, they remain in the hierarchy until explicitly removed using unlink, but pipes are inherited only by related processes, that is, processes which are descendants of a single process.

Let us see how a fifo can be used to detect a keypress, just as we did with pipes. The same program where we previously used a pipe can be modified and implemented using a fifo.
(Text version: write-fifo.c.txt)
/***** PROGRAM THAT READS ANY KEY HIT OF THE KEYBOARD*****/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

extern int errno;

void *read_char()
{
 char c;
 int fd;
 printf("Entering routine to read character.........\n");
 while(1) {
  c = getchar();
  fd = open("fifo", O_WRONLY);
  if(c == '\n')
   c = getchar();
  write(fd, &c, 1);
  if(isalnum(c)) {
   exit(1);
  }
  close(fd);
 }
}

int main()
{
 int i;
 pthread_t tid1;
 i = mkfifo("fifo", 0666);
 if(i < 0) {
  printf("Problems creating the fifo\n");
  if(errno == EEXIST) {
   printf("fifo already exists\n");
  }
  printf("errno is set as %d\n", errno);
 }
 i = pthread_create(&tid1, NULL, read_char, NULL);
 if(i == 0) while(1);
 return 0;
}
Compile this program using cc -o write_fifo filename.c. This program reads characters (keypresses), and writes them into the special file fifo. First the program creates a fifo with read-write permissions using the function mkfifo. See the manual page for the same. If the fifo exists, then mkfifo will return the corresponding error, which is set in errno. The thread read_char continuously tries to read characters from the keyboard.
Note that the fifo is opened with the O_WRONLY (write only) flag .
Once it reads a character other than '\n', it writes the same into the write end of the fifo. The program that detects it is given below: (text version detect_hit.c.txt):
/***** KEYBOARD HIT PROGRAM *****/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>

extern int errno;

void *check_hit()
{
 char c;
 int fd;
 int i;
 printf("Entering routine to check hit.........\n");
 while(1) {
  fd = open("fifo", O_RDONLY);
  if(fd < 0) {
   printf("Error opening in fifo\n");
   printf("errno is %d\n", errno);
   continue;
  }
  i = read(fd, &c, 1);
  if(i < 0) {
   printf("Error reading fifo\n");
   printf("errno is %d\n", errno);
  }
  if(isalnum(c)) {
   printf("The key hit is %c\n", c);
   exit(1);
  } else {
   printf("key hit is %c\n", c);
  }
 }
}
  
int main()
{
 int i;
 i = mkfifo("fifo", 0666);
 if(i < 0) {
  printf("Problems creating the fifo\n");
  if(errno == EEXIST) {
   printf("fifo already exists\n");
  }
  printf("errno is set as %d\n", errno);
 }
 pthread_t tid2;
 i = pthread_create(&tid2, NULL, check_hit, NULL);
 if(i == 0) while(1);
 return 0;
}
Here, again, it first tries to create a fifo which is created if it does not exist. We then have the thread check_hit which tries to read characters from the fifo. If the read character is alphanumeric, the program terminates; otherwise the thread continues reading characters from the fifo.
Here, the fifo is opened with the flag O_RDONLY.
Compile this program with cc -o detect_hit filename.c. Now run the two executables in separate terminals, but in the same working directory. Irrespective of the order in which you run, look for the message fifo already exists on the console. The first program (either of the two) that you run will not give any error message for creation of the fifo. The second program that you run will definitely give you the error for creation of the fifo. In the terminal where you run write_fifo, give input to standard output from your keyboard. You will get the message regarding the key hit on the keyboard on the terminal running the executable detect_hit. Analyze the working of the two programs by hitting several keys.
I have used two different programs for exhibiting the usage of fifos. This can be done within a single program by forking the routines which are called in the two program as threads. But I did this to show that unlike pipes, fifos can be used for communication between unrelated processes.
Now try running the program again. You will get the message that the fifo already exists even when you first run either of the two programs. This shows that fifos are persistent as long as the system lives. That is, the fifos will have to be removed manually - otherwise they will be permanently recognized by the file system. This is unlike pipes which are inherited as long as the process that created the pipe is running. Once this process dies, the kernel also removes the identifiers (file descriptors) for the pipe from the the file tables.

The usage is rather simple and the main advantage is that there is no need for any synchronization mechanism for accesses to the fifo. There are certain disadvantages: they can only be used for communication between processes running on the same host machine. Let us explore other IPC mechanisms to see what have they in store.

Pipes vs Fifo

A pipe is a mechanism for interprocess communication; data written to the pipe by one process can be read by another process. The data is handled in a first-in, first-out (FIFO) order. 

The pipe has no name it is created for one use and both ends must be inherited from the single process which created the pipe.

A FIFO special file is similar to a pipe, but instead of being an anonymous, temporary connection,

a FIFO has a name or names like any other file. Processes open the FIFO by name in order to communicate through it. 

A pipe or FIFO has to be open at both ends simultaneously. If you read from a pipe or FIFO file that doesn't have any processes writing to it (perhaps because they have all closed the file, or exited), 

the read returns end-of-file. Writing to a pipe or FIFO that doesn't have a reading process is treated as an error condition; it generates a SIGPIPE signal, and fails with error code EPIPE if the signal is handled or blocked. 

The only difference between pipes and FIFOs is the manner in which they are created and opened. Once these tasks have been accomplished, I/O on pipes and FIFOs has exactly the same semantics.

Shared Memory

Shared Memory is one of the three kinds of System V IPC mechanism which enables different processes to communicate with each other as if these processes shared the virtual address space; hence, any process sharing the memory region can read or write to it. One can imagine some part of memory being set aside for use by different processes.
The System V IPC describes the use of the shared memory mechanism as consisting of four steps. Taken in order, they are:
  • Fetching an identifier for the shared memory area - shmget (shared memory get)
  • Using the identifier to get the shared memory address - shmat (shared memory attach),
  • Detaching the shared memory area after use - shmdt (shared memory detach) and
  • Finally using the address to control accesses, permissions, receive information and destroy the shared memory area - shmctl (shared memory control).
Let us examine the workings of the above system calls. Recall the keyboard hit program; we shall, once again, see another version of it, this time using the system calls associated with the shared memory mechanism.
The code given below creates a shared memory area and stores the information of any key hit on the keyboard. Let us see the code first: (text version: write-shm.c.txt)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>

extern int errno;

#define SIZE 1

char *read_key;
int shmid;

int shared_init()
{
 if((shmid = shmget(9999, SIZE, IPC_CREAT | 0666)) < 0) {
  printf("Error in shmget. errno is: %d\n", errno);
  return -1;
 }
 if((read_key = shmat(shmid, NULL, 0)) < 0) {
  printf("Error in shm attach. errno is: %d\n", errno);
  return -1;
 }
 return 0;
}

void read_char()
{
 char c;
 while(1) {
  c = getchar();
  if(c == '\n') {
   c = getchar();
  }
  strncpy(read_key, &c, SIZE);
  printf("read_key now is %s\n", read_key);
  if(isalnum(*read_key)) {
   shmdt(read_key);
   shmctl(shmid, IPC_RMID, NULL);
   exit(1);
  }
 }
}

int main()
{
 if(shared_init() < 0) {
  printf("Problems with shared memory\n");
  exit(1);
 }
 read_char();
 return 0;
}
Here we have a shared memory variable named read_key. The program first initializes the shared memory area read_key. This is done by generating a shared memory identifier shmid using the system call shmget. In the context of the program, the first parameter for shmget is 9999, which is the key. This key is used to allocate a shared memory segment. The second parameter, SIZE (defined as a macro with the value 1), suggests that the shared memory segment will hold only one of the type of the shared memory variable, that is, only 1 character. The IPC_CREAT flag (third parameter) suggests that a new shared memory segment has to be created, with read-write permissions (IPC_CREAT logically OR ed with 0666). This will return a valid shared memory segment identifier on successful allocation. The identifier will be stored in shmid. If shared memory segment allocation fails, then -1 is returned and the errno is set appropriately.
The key which is used to get a shared memory segment can be generated randomly using the built-in function ftok to get a unique key. Refer to the manual page for the usage.
Once the segment identifier is obtained, we have to attach the shared memory segment to some address. This is done with the shmat system call. This uses the segment identifier shmid as the first parameter. The second parameter is the address of the shared memory segment; when this is given as NULL (as in this program), the kernel will choose a suitable address. The third parameter is the flag specification which can be set if required or left as zero (see man page of shmdt for details). On success the shared memory segment is attached to read_key, otherwise -1 is returned along with the appropriate setting of the errno.
If either shmget or shmat fails, the process terminates. On success from both system calls, we proceed by invoking the read_char function, which reads keyboard inputs other than '\n' ("Enter" key) and copies them to read_key in the shared memory. If the keyboard input is an alphanumeric character, the program stops reading inputs from the keyboard and the process terminates.
We have another program running separately (it does not have to be in the same working directory) in the local system, which tries to read the data written in the shared memory area. The code is given below: (text version: read-shm.c.txt)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>

extern int errno;

#define SIZE 1

char *detect_key;
int shmid;

int shared_init()
{
 if((shmid = shmget(9999, SIZE, 0444)) < 0) {
  printf("Error in shmget. errno is: %d\n", errno);
  return -1;
 }
 if((detect_key = shmat(shmid, NULL, SHM_RDONLY)) < 0) {
  printf("Error in shm attach. errno is: %d\n", errno);
  return -1;
 }
// detect_key = NULL;
 return 0;
}

void detect_hit()
{
 char c;
 c = *detect_key;
 while(1) {
  if(c != *detect_key) {
   if(isalnum(detect_key[0])) {
    printf("detect_key is %s\n", detect_key);
    shmdt(detect_key);
    shmctl(shmid, IPC_RMID, NULL);
    exit(1);
   } else {
    printf("detect_key is %s\n", detect_key);
   }
   c = *detect_key;
  }
 }
}

int main()
{
 if(shared_init() < 0) {
  printf("Problems with shared memory\n");
  exit(1);
 }
 detect_hit();
 return 0;
}
Here, again, we have a shared memory initialization routine, which in fact does not create a new shared memory segment, but rather tries to get access to the existing shared memory segment. Compared to the previous program, the absence of IPC_CREAT flag suggests that we do not have to create a new shared memory segment. Instead, we simply have to get the corresponding segment identifier which can be used to attach the existing shared memory segment to some address. The mode 0444 restricts access to the shared memory segment to 'read only'. If no shared memory segment with key 9999 exists, we will get an error, which will be returned in errno. Once we get a valid identifier, we attach the shared memory segment to an address. While attaching, we use the flag SHM_RDONLY which specifies that the shared memory segment will be available only for reading.
Next, we have the function detect_hit, which checks whether the pressed key was an alphanumeric character. The first program obviously has to run first; otherwise, the second program will show errors during the shared memory initialization, since it would be trying to get the identifier for a non-existent shared memory segment.
The example shown here doesn't require any synchronization of access to the shared memory segment. That is because only one program writes into the shared memory and only one program reads from the shared memory area. But again, there is a problem here. What if the detection program (second one) is started long after some user has started hitting the keys (running the first program)? We will not be able to track the previously hit keys. The solution for this is left as an exercise to the readers.
The entry in /proc/sysvipc/shm gives a list of shared mermory in use. Readers can compare the entries before running, during running and after running the programs. Try to interpret the entry in /proc/sysvipc/shm.
Once the two programs identify an alphanumeric character, they will terminate. As part of that process, the shared memory area is detached by using the system call shmdt. In fact, upon exiting the detaching is done automatically. But the shared memory segment is not destroyed. This has to be done by invoking the system call shmctl, which takes the identifier for the shared memory area as an argument, as well as the command IPC_RMID, which marks the shared memory segment as destroyed. This has to be done, otherwise the shared memory segment will persist in memory or in the swap space.
At this point, observation of the entries in /proc/sysvipc/shm can be very useful. If the shared memory segment is not destroyed, the entries will reflect this. Try this by running the program without shmctl.
This is the fastest IPC mechanism in the System V IPC services. However, the System V shared memory mechanism does not have any kind of scheme to ensure that one sees consistent data in the shared memory region. That is, a process can read a shared memory area at the same time another process is writing to it. The programmer can then come across inconsistent data while executing the programs. This suggests that accesses to the shared memory region have to be mutually exclusive; this is achieved via the use of the semaphore mechanism. We can make the semaphore access the memory region to lock it and then release the semaphore when done.
The shared memory mechanism can be used when the processes access the shared memory areas at different times. One may wonder why we can't make the first process store the data in some file and make another process read the data from the file. But, reading data from a file involves things like:
  • execution of system calls like open, read and close.
  • accessing the secondary storage device (generally hard disk) which involves I/O operations.
These things are not significant if we have a small amount of data to be read. But when we have large amounts of data stored in a file, then the load of the two activities mentioned above increases significantly and there is a considerable amount of reduction in the performance of the "reading program". This, again, has a solution, which is the use of memory mapping - something I'll discuss at another time.

Friday, September 24, 2010

C++ Professional Schdule

I am creating schedule for c++ professional which is mainly applicable to me :) but can be helpful for others. As a C++/Python Programmer, we should have good knowledge  in below topic.


C++                        http://cppcoffe.blogspot.in/2012/07/blog-post.html


Data Base              http://cppcoffe.blogspot.in/p/data-base.html
        
Python                   http://cppcoffe.blogspot.in/p/python-skill-and-interview.html



 STL              http://cppcoffe.blogspot.in/p/stl-url.html 

Coding website                              

Friday, August 20, 2010

c++ notes 2

Protected member function can not access into main function but it can be access into the derived class.


What is virtual base class.

When we write two derived class derive from the base class than we write new derive class which also derive two above class. It is called the virtual base class.

Code:
Class Base
{
Public:
Int data;
Base()
{
Data =0;
}
};

Class derived : virtual public Base
{
};
Class derived1 : virtual public Base
{
};

Class derived3 : public derived , public derived
{
Public:
Int getdata()
{
Return data;
}
};
Int main()
{
Derived d3;
Int a =d3.getdata();
}

a)Some changes if we remove virtual keyword from the derived class.
Than it will be compiler error.

base.cpp: In method `int derived3::getdata()':
base.cpp:37: request for member `data' is ambiguous in multiple inheritance lattice
base.cpp:8: candidates are: int base::data
base.cpp:8: int base::data

http://stackoverflow.com/questions/1321062/object-layout-in-case-of-virtual-functions-and-multiple-inheritance

http://www.phpcompiler.org/articles/virtualinheritance.html

http://www.ziddu.com/download/16618915/jangrayhood.pdf.html


b) if we write public virtual Base rather than virtual public Base than it does not impact anything Program run successfully.

Virtual  keyword 


Class base
{
Public:
void fun()
{
Cout<<” base::fun()”<<endl;
}
};

Class derived : public Base
{
Fun()
{
Cout<<” derived ::fun()”<<endl;
}
}

Int main()
{
Base *p,base;
Derived d;
P=&base;
p->fun();
p=&d;
p->fun();
}


Output :

Base ::fun()
Base ::fun()

if virtual keyword than
 
Output:

Base ::fun()
Derived ::fun()

Third Case

Class Base
{
Public:
Void virtual fun() - There is no error if u write virtual void or void virtual
{
Cout<<” base :: fun”<<endl;
}

};
Class derived :public base
{
Public :
Void fun()
{
Cout<<” derived::fun”<<endl;
}
};
Int main()
{
Base *p,base;
Derived d;
P=&base;
p->fun();
p=&d;
p->fun();
return 0;
}


Output
Base ::fun()
Derived ::fun()


Fourth Case


Class Base
{
Public:
Virtual void fun()
{
Cout<<” Base:: fun()”<<endl;
}
};
Class derived : public base
{
Public:
fun()  Change the signature from the base class
{
Cout<<” Derived :: fun()”<<endl;
}

Int main()
{

Base *b,base;
Derived d;
b=&base;
b->fun();
b=&d;
b->fun();
}


Output:

virtual.cpp:22: ANSI C++ forbids declaration `fun' with no type
virtual.cpp:22: conflicting return type specified for virtual function `int derived::fun()'
virtual.cpp:8: overriding definition as `void base::fun()'

Fifth Case:

Class Base

{
Public :
Virtual void fun()
{
Cout<<”Base::fun()”<<endl;
}
};
Class derived : public Base
{
Public :
I have removed fun function from the derived class
}
Int main
{
Base *p,base;
Derived d;
p=&base;
p->fun();
p=&d;
p->fun();
}

Output

Base ::fun()
Base ::fun()

Case Sixth

Class Base
{
Public:
Void fun()
{
Cout<<” Base::fun()”<<endl;
}
};
Class derived : public Base
{
Public:
Virtual void fun()  Adding virtual keyword in the derived class
{
Cout<<” Derived::fun()”<<endl;
}
};
Int main()
{
Base *p,base;
Derived d;
P=&base;
p->fun();
p=&base;
p->fun();
}

output
Base ::fun()
Base ::fun()

Case Seven

class base{
public :
virtual void fun()
{
   cout<<" Base ::fun()"<<endl;

}
};


class derived : public base
{
   public:
   void fun()
   {
           cout<<" derived::fun()"<<endl;
    }


   void method()
   {
           cout<<" base::method::fun()"<<endl;
    }


}


int main()
{
    base *p;
    derived d;
    p=&d;
    p->method();
 }

Output: 


virtual.cpp: In function 'int main()':
virtual.cpp: error: 'class base' has no member named 'method'


Case Eight C) wrong syntax




We can write base class in following way
a) Correct Syntax

Int main()
{
Base *p,base;
Derived d;
P=&base

p->fun();
p=&d;
p->fun();
}


b) Correct Syntax
int main()
{
Base *p,base;
Derived d;
p=new derived;
p->fun()
}



Int main()
{
Derived *d,d1;
Base base;
d =new base
d->fun();
d=&d1;
d->fun();
}

Error: type `derived' is not a base type for type `base'

d) wrong syntax
int main()
{
Derived *d,d1;
Base base;
D=&base;
d->fun();
d=&d1;
d->fun();
}
Error : type `derived' is not a base type for type `base'

What is virtual function

A virtual function or virtual method is a function or method whose behavior
Can be overridden within an inheriting class by a function with the same signature

What is kind of and has a relationship
What is iterator and iteration

Iterator is an object which moves in the container from the one element to another element and access the variable. The process of moving one element

From another element called iteration
When should the explicit keyword be used in the constructor ?

When we want that constructor should create object but it should not perform any
Implicit conversion than we should use the explicit keyword.


#include<iostream>
Class sample
{
Int I;
Explicit Sample(int ii =0)
{
I=ii;
}

Sample operator+(sample s)
{
Sample temp;
temp.i =i+s.i;
return temp;
}
Void display()
{
Cout<<I;
}
}
Int main()
{
Sample s1(15),s2;
S2=s1+15; //compilation error
S2.display();
}

How will you change the data member of the const object.

To change the date member of the const object the data members are declared
As mutable in the class.

#include<iostream>
Class sample
{
Private:
Mutable int I; - Mutable keyword
Public:
Sample(int ii=0)
{
I=ii;
}
Void fun() const  const object can access const function
{
I++;
}
};
Int main()
{
Const sample s(15);  const object.
s.fun();
}

More info about Const Variable.
http://www.cprogramming.com/tutorial/const_correctness.html

http://www.parashift.com/c++-faq-lite/const-correctness.html 

http://duramecho.com/ComputerInformation/WhyHowCppConst.html

What is friend function and when should be a function be made friend

A global function that can access that all data member of a class is called a friend function of that class. To make any function a friend of class it must be declared with the keyword friend function.

A function is made friend in the following two cases.
To access private data of a class from a non member function

To increase the versatility of overloaded operator
How does a friend function help in increasing the versatility of the overloaded operators

S2=s1*2
Where s1 and s2 are objects of the sample class. The statement works if the overloaded operator * (sample s) or conversion function is provided in the class.

Internally this statement occurs
S2=s1.operator*(2);

The function materializes because it is called with an object S1 the this pointer
Of s1 implicitly get passed.

But if we want to write the above statement as
S2=2*s1;

#include<iostream>
Class sample
{
Private
Int I;
Public:
Sample(int ii =0)
{
I =ii;
}
Void showdata()
{
Cout<<i<<endl;
}
Friend sample operator*(sample,sample);
};
Sample operator*(sample s1,sample s2)
{
Sample temp;
Temp.i=s1.i +s2.i;
Retrun temp;
}
Int main()
{
Sample s1(10),s2;
S2=s1*2;
S2.showdata();
S1=s2*2;
S1.showdata();
}

What is forward referencing and when should be used?

Class sample
{
Public:
Friend void fun(sample,test);
};
Class test
{
Public:
Friend void fun(sample,test);
}

Int main()
{
Sample s;
Test t; }

Write one case where friend function becomes necessary

When we want user user defined object should be print through cout than we overload operator <<.

Class sample
{
Char name[20];
Int age;
Float sal;

Public:
Friend ostream& operator<<(ostream &o, sample &a);
Friend istream& operator>>(istream &I,sample &a);
}
Ostream& operator<<(ostream &o, sample &a)
{
O<<a.name<<a.age<<a.sal;
Return o;
}
Istream& operator>>(istream &I, sample &a)
{
i>>a.name>>a.age>>a.sal;
return I;
}
Int main()
{
Sample s;
Cin>>s;
Cout<<s;
}

Is it necessary that while using pointer to member with data the data must be made public

Yes the private data member are never accessible outside the class

How would you define a point to data member of the type pointer to pointer

Class sample
{
Public:
Sample(int **pp)
{
p=pp;
}
Int **p;
}
Int **sample:: *ptr = &sample::p;
Int main()
{
Int i=9;
Int *s =&I;
Sample sa(&s);
Cout<<**(s.*ptr);
}

Can we create a pointer to member function
Class sample
{
Public:
Void fun()
{
Cout<<”func with the pointer”<<endl;
}
};
Void (sample:: *pfun()) =&sample::fun;
Int main()
{
Sample s;
(s.*pfub()) ();
}

Some more info
http://www.eskimo.com/~scs/cclass/int/sx10b.html

What is namespace

While developing a program different header file are included. It may happen that some header file contain same function or class name. Trying to access these function or classed may lead to be an ambiguity. Such ambiguity can be

Avoided using namespace.
How to refer to a name of class or function that is defined within a namespace

Namespace name1
{
Class sample1
{
//code
}
}
Namespace name2
{
Class sample2
{
//code
}
}
Using namespace sample2;
Int main()
{
Name1:: sample s1;
Sample2 s2;
}


What is RTTI

RTTI stands for run time type identification. In the inheritance hierarchy using RTTI we can find exact type of object using a pointer or reference to the base class. The idea behind that virtual function is to upcast the derived class objectAddress into a pointer to a base class object and then the virtual function

Mechanism implement the correct behavior.

Thursday, August 19, 2010

c++ Notes

Constructor:

Class X
{
int i;
public:
X();
}
void f() is
{
X a;
}
the same thing happen as if a were an int. Storage is allocated for object But when the program reaches the sequence point(point of execution) where a is defined, the constructor is called automatically. That is, the compiler quietly insert the
call to X::X() for the object a at point of definition. like any member function the first secret argument to the constructor is the this pointer the address of the object for which it is being called .in the case of constructor however this is pointing  to an unintialized block of memory and it is job of the constructor to intialize this memory properly.

If u have constructor with the argument than you can initialize object with argument. Tree a(2).

Constructor and destructor can not have return value.
In the Destructor never has any argument because destruction never need any option.
Class Y {
Public:
~Y();
};

Example of constructor and destructors
#include<iostream>
Using namespace std;

Class Tree
{
Int height;
Public :
Tree( initialHeight);
~Tree();
Void grow(int years);
Void printsize();
Void grow(int years);
Void printsize();
};
like any function, the constructor can have argument to allow you to specify how an object is created.
A default constructor is one that can be called with no argument.

Storage allocation:

A variable can now be defined at any point in a scope. So it might seem that the storage for the variable may not be defined until its point of definition.
The storage is allocated at the beginning begining of the block, the constructor
Call does not happen until the sequence point where the object is defined because the identifier is not available until then.


Aggregate initialization
 
An aggregate is just what it sounds like : a bunch of things clumped together.

This definition includes aggregates of mixed types like struct and classes. An array is an aggregate of a single type.
When you create an object that’s an aggregate all you must do is make assignment and the initialization will be taken care of by the compiler.
This assignment can be in several flavors For an array of built in type this is quite simple
Int a[5] ={1,2,3,4,5}
If u try to give more initializers than there are array element , the compiler gives an error message.
Int b[6] ={0}
A second shorthand for arrays is automatic counting in which you let the compiler
Determine the size of the array based on the number of initializers.
Int c[] ={ 1,2,3,4 }

Now if you decide to add another element to the array you simply add another initialize.

The size of array will be sizeof c /sizeof *c ( size of the entire array deivided by the size of the first element)

For(int I =0; i< sizeof c/ sizeof *c ;i++)
C[i]++;

Structure are also aggregates , they can be initialized in a similar fashion. Because a C style struct has all of its members.

Struct X
{
Int I;
Float f;
Char c;
};

X x1 ={1,2.2.’c’}
If you have an array of such object you can initialize them by using a nested set of curly braces for each object.
X x2[3] ={ {1,1.1,’a’} , {2,2.2.,’b’}}
Here the third object is initialized to zero.

If you have struct with all members public or a class with private data member all the initialization must go through the constructor even if you are using aggregat Initialization.

Second example showing multiple constructor argument.

#include<iostream>
Using namespace std;

Class z {
Int I,j;
Public:
Z(int ii ,int jj);
Void print ();
};
Z::Z(int ii , int jj)
{
I =ii;
J=jj;
}

Void Z::print() {
Cout<<” I =”<<I <<” j=”<<j<<endl;
}

Int main()
{
Z zz[] = { Z(1,2) ,Z(3,4) , Z(5,6) ,Z(7,8) };
For(int I =0 ; i< sizeof zz / sizeof *zz ; i++)
Zz[i].print();

Notice that it look like an explicit constructor is called for each object in the array.
}

Default constructor:
A default constructor is one that can be called with no argument. A default constructor is used to create a “vanilla object” but it is also important when the

Compiler is told to create an object but is not given details.
For Example if you take the struct Y defined previously and use it in a definition like this .
Y y2[2] ={ Y(1) };
The complier will complain that it can not find a default constructor.
The second object in the array wants to be created with no argument
And that’s where the compiler looks for a default constructor.
In fact if you simply define an array of objects
Y y3[7];
The complier will complain because it must have a default constructor to initialize every object in the array.
The default constructor is so important if and only if there are no constructor for a constructor

Function overloading and default argument
More name decoration

The concept of name decoration was introduced.
Void f()
Class X
{
Void f();
}
The function f() inside the scope of class X does not clash with the global version of f().
The compiler perform this scoping by the manufacturing different internal name for the global version of f()and X::f().

It was suggested that the name are simply the class name “decorated” together
Function name so the internal names the compiler uses might be _f and _X_f.
The compiler will give the name with the argument list with function name. it does not generate compiler name only with the function name.

Overloading does not depend on the return value

Type Safe linkage

There is an added benefit to all of this name decoration. A particularly sticky problem in c occurs when the client programmer misdeclares function or worse a function is called without declaring it first and the compiler infers the function declaration from the way it is called. Sometimes this function declaration is correct but when it is not it can be a difficult bug to find.

Because all functions must be declared before they used in c++ . the opportunity for this problem are very rarely.
The c++ compiler refuses to declare a function automatically for you . so it is likely that you will include the appropriate header file.
However if for some reason you still manage a misdeclare a function either by declaring by hand or including the wrong header file the name decoration provides a safety net that is often referred to as type safe linkage.
Consider the following scenario. In one file is the definition for the function.
Void f(int){}
In the second file the function is not declare properly then called.
Void f(char);

Int main() {

// f(1)
}

Even though you can see that the function is actually f(int) the compiler does not know because it was told – through the explicit declaration that the function is f(char). Thus the compilation is successful.

In c the linker would also be successful but not in c++ Because the complier decorates the names the definition becomes something like f_int whereas the use of the function is f_char.

When the linker tries to resolve the reference to f_char it can only find f_int and give you error message.

Overloading Example

We can now modify earlier example to use function overloading.

As stated before an immediately useful place for overloading is in constructor.

You can see this in the following version of the stash.

Class Stash
{
Int size;
Int quantity;
Int next;

Unsigned char* storage;
Void inflate(int increase);

Public:
Stash(int size);
Stash(int size , int initQuantity);

~Stash();
Int add(void *element);
Void *fetch(int index);
Int count();

};

The first stash() constructor is the same as before but the second one has a Quantity argument to indicate the initial number of the storage places to b Allocated.
In the definition, you can see that the internal value of quantity is set to zero.Along with the storage pointer.

Overloading does not depend on the return value.


Unions

As you have seen the only difference between struct and class in C++ is that Struct default to public and class default to private.

Union can also have a constructor, destructor ,member function and even access control.


#include<iostream>
Using namespace std;

Union U {

Private:
Int I;
Float f;

Public :
U(int a);
U(float b);

~U();
Int read_int();
Float read_float();
};

U::U(int a)
{
I=a;
}
U::U(float b) { f =b; }
U::~U()
{
Cout<<” U::~U()\n”; }

Int U:: read_int()
{ return I;
}

Float U :: read_float()
{
Return f;
}

Int main()
{
U X(12),Y(1.9F);
}

You might think from the code above that the only difference between a union and class is the way the data is stored. ( int and float are overlaid on the same piece of storage).

Union can not be used as a base class during inheritance.

Although the member functions civilize access to the union somewhat there is still no way to prevent the client programmer from the selecting the wrong element type once the union is initialized.


In the example above you could say X.read_float() even though it is inappropriate.( you are float function to integer object)

However a “safe” union can be encapsulated in a class.


#include<iostream>

Using namespace std;


Class SuperVar {
Enum {
Character,
Integer,
Floating_point
}varitype;


Enum has no typename ( it is untagged enumeration) .This is acceptable if you are going to immediately define instances of the enum


Union {
Char c;
Int I;
Float f;
};


The union has no type name and no variable name. This is called an anonymous union and create space for union but does not require accessing the union element with a variable name and dot operator.


Public:
SuperVar(char ch);
SuperVar(int ii);
SuperVar(float ff);
Void print();


};


SuperVar::SuperVar(char ch)
{
Vartype =character;
C=ch;
}


SuperVar::SuperVar(int ii)
{
Vartype =integer;
I=ii;
}


SuperVar::SuperVar(float ff)
{
Vartype =floating_point;
F= FF;
}
Void SuperVar::print() {
Switch(vartype) {
Case character :
Cout<<” character “<<c<<endl;
Break;
Case integer :
Cout<<”integer “<<i<<endl;
Break;
Case floating_point:
Cout<<”float”<<f<<endl;
Break;
}
}


Int main()
{
SuperVar A(‘c’), B(12),c(1.4F);
}


The first purpose of the union in the first place to save union.

Default argument:



C++ provides a remedy default argument. A default argument is a value given in the declaration that the compiler automatically inserts if you do not provide a value in the function call.
Stash(int size);


Stash(int size, int quantity =0);

Default arguments are a convenience as function overloading is a convenience.
Both feature allow you to use a single fuction name in different situation.


The difference is that with default arguments the complier is substituting argument when you do not want to put them in yourself.
If the function have very different behaviors it does not make sense to use default argument.


There are two rules you must be aware of when using default argument.
First only trailing argument may be defaulted .That ‘s you can not have
A default argument followed by the non default argument.


Once you start using default argument in a particular function call , the subsequent argument in that function’s argument list must be defaulted.


Function overloading simple facts

http://codepad.org/LfOfvwOj

http://codepad.org/2ETEJcEG#comment-Yk8miiVk

http://codepad.org/tWoRl7dN

http://msdn.microsoft.com/en-us/library/kbd4xa4d.aspx

 

Placeholder Argument

Argument in a function declaration can be declared without identifiers.Const in header file
A const in C++ defaults to internal linkage that is it is visible only within the file where it is defined and can not be seen at link time by other translation unit. You must always assign a value to const where it is defined and can not seen at the link by the other translation unit. You must always assign a value to a const when


You define it. Expect when you make an explicit declaration using extern.



  • Extern const int bufsize :Normally the C++ compiler avoid creating storage for a const but instead hold the  Definitions in its symbol table. When we extern keyword it forces us to allocate storage.
           Extern says “use external linkage”

Safety Consts
The use of const is not limited to replacing #define in constant expression. If you initialize a variable with a value that is produced at the runtime and you will not change for the lifetime of that variable.

#include<iostream>
Using namespace std;
Const int i=100;
Const int j= i+10;
Long address =(long)&j;
Char buf[j+10];


Int main()
{
Cout<<” type a character”<<endl;
Const char c= cin.get() //can not chage
Const char c2 =c+’a’;
Const<<c2;
}


Difference with C++
The meaning of const in C “an ordinary variable that can not be changed”
In C a const always occupies storage and its name is global. The C compiler can not treat const as compile time constant.

In C if you say
Const
int bufsize =100;
Char buf[bufsize];

You will get an error even though it seems like a rational things to do. Because bufsize occupies storage somewhere. The C compiler can not know the value at compile time. You can optionally say

Const int bufsize;
C defaults to external linkage for consts this make sense. C++ defaults to internal linkage for const . So if you want to accomplish the same things in c++

You must explicitly change the linkage to external using extern.
Extern const int bufsize;

This line also works in C.
In C++, a const does not necessarily create storage. In C a const always create

Storage.
In C++ a const that is outside all function has file scope (i.e. it is invisible outside
The file. That is, it is default to internal linkage.

This is very different from all other identifiers in c++ that default to external linkage. Thus if you declare a const of the same name in two different file

And you do not take the address or define that name as extern. The ideal c++
Compiler will not allocate storage for the const but simply fold it into the code.

PointerWhen using const with pointer you have two options
Const can be applied to what the pointer is pointing to.

Const can be applied to the address stored in the pointer itself.

Pointer to Const
So if you want to prevent any changes to the element you are pointing to you write a definition like this.

Const int *u;
U is a pointer which points to a const int

Int const *V
V is const pointer to an int

Both the effect are same.
Const pointer

Int d =1;
Int * const w= &d;

W is pointer which is const that point to int.
Assignment and type checking

C++ is very particular about type checking and this extends to pointer assignment. You can assign the address of a non const object to a const

Pointer because you are simply promising not to change something that is
Ok to change.
You can not assign the address of a const object to a non const pointer.

Character array literals
The place where strict constness is not enforced is with character array literals.
Char *cp =”howdy”

The compiler will accept it without complaint. This is technically an error because

Because a character array literal is created by the compiler as a constant character array and the result of the quoted character array is its starting address

In memory.
If you want to be able to modify the string put it in an array
Char cp[] =”howbdy”

Function arguments & return values
Passing by const value
You can specify that function arguments are const when passing them by value such as

Void f1(const int i) {
I++; compile time error
}
The const takes on meaning the argument can not be changed .so it is really tool
For the creator and not the caller.

Returning by the const value
A similar truth hold for the return value. If you say that function’s return value is const.
Const int g().

You are promising that original variable will not be modified inside the function.
Int f3() { return 1;}

Const int f4() { return 1; }
Int main()
{
Const int j =f3(); //works fine
Int k =f4(); // But this works fine too
}
For built in types it does not matter whether you return by value as const so you avoid confusing the client programmer and leave off the const when returning a built in type by value.

Returning by value as a const becomes important when you are dealing with user defined types.
Class X {
Int I;
Public:
X(int ii =0);
Void modify();
};

X::X(int ii)
{
I =ii;
}

Void X::modify()
{
I++;
}

X f5() - No constant
{
Return X();
}

Const X f6() { - Return Constant
Return X();
}

Void f7(X& x)  Pass by Const
{
x.modify();
}
}

Int main()
{
F5() = X(1); //ok non const return value
F5() return a non const X object while f6() return a const X object. Only the non const return value can be used as an lvalue.

Passing and returning addresses
Page No 349 (Thinking in c++)

If you pass or return an address( either a pointer or reference) it’s possible for the client programmer to take it and modify the original value.
If you make the pointer or reference a const you prevent this from happening.
In fact when you are passing an address into a function, you should make it a const if at all possible.

The choice of whether to return a pointer or reference to a const depends on what you want to allow your client programmer to do with it.

Void t(int *) { } - ordinary pointer
Void u(const int* cip)
{
*cip =2 // illegal Modifing value.
Int I = *cip // ok copies value
Int *p2 =cip // illegal non const value
}


Const char *v() {
// Return address of static character array
Return “result of function v()”
}

Const int * const w () {
Static int I;
Return &I;
}

Int main()
{
Int x =0;
Int *ip =&x;
Const int *cip =&x;
T(ip); //ok
// t(cip) //Not ok you can not assign const pointer to non const pointer
U(ip) //ok

U(cip) // ok
Char *cp =v() // not ok
Const char *ccp =v(); //ok
Int *ip2 =w(); //Not ok

Const int* const ccip =w(); //ok
Const int* cip2 =w() //ok
*w() =1 // Not ok

}

Standard argument Passing
In C it is very common to pass by value and when you want to pass an address your only choice is to use pointer.
In C++ your first choice pass by reference and by const reference at that.
Because of the syntax reference, it is possible to pass a temporary object to a function that takes a const reference. In the other case you can never pass a temporary object to function that takes a pointer.

With a pointer, the address must be explicitly taken.
The example will better explain.

ConstTemporary.cpp
Class X {};
X f() { return X(); }
Void g1(X&) {} // Pass by the non const reference.


Void g2(const X&) { }
Int main()
{
// g1(f())
// Error: const temporary created by the ()
// g2(f())
}

F() returns an objects of class X by value. That means when you immediately take the return value of f() and pass it to another function as in the calls to g1() and g2(), a temporary is created and that temporary is const.

The call in g1() is an error because g1() does not take a const reference but the call to g2() is ok

Classes
This section shows the way you can use const with classes. You may want to create a local const in a class to use inside constant expression that will be

Evaluated at the compile time.
Const in classes
One of the places you did like to use a const for constant expression is inside classes. The typical example is when you are creating an array inside a class

And you want to use a const instead of a #define to establish the array size
And to use in calculation involving the array. The array size is something you did like to keep hidden inside the class. So if you used a name like size for example

You could use that name in another class without a clash.
The preprocessor treats all #define as global from the point they are defined, so

This will not achieve the desire effect.

The constructor initialize list
The special initialization point is called the constructor initialize list and it was originally developed for use in inheritance.

The constructor initializer list – which as the name implies, occur only in the definition of the constructor.
The proper form for const inside a class is shown here.

#include<iostream>
Using namespace std;
Class Fred
{
Const int size;
Public:
Fred(int sz);
Void print()
};

Fred :: Fred(int sz) : size(sz) {}
Void Fred :: print() { cout <<”size “<<endl}

Int main()
{
Fred a(1),b(2),c(3);
a.print(),b.print(),c.print();
}

“Constructor” for built in type
You can treat a built in type as if it has a constructor like this.


#include<iostream>
Using namespace std;

Class B
{
Int I;
Public:
B(int ii);
Void print()
};

B::B(int ii) : i(ii) { }
Void B::print() {
Cout<<I <<endl;
}

Int main()
{
B a(1),b(2);
}

Compile time constants in classes
The above use of const is interesting and probably useful in cases but it does not solve the original problem.

The static keyword in this situation means “there is only one instances regardless of how many objects of the classes are created”
There is one feature of static const when used inside the classes which is bit unusal, you must provide the initialize at the point of definition of the static const

#include<string>
#include<iostream>

Using namespace std;
Class StringStack
{
Static const int size =100;
Const string* stack[size];

int index;
}
The “enum hack” in old code
In older version of c++, static const was not supported inside classes. This meant

The const was useless for constant expression inside the classes.
#include<iostream>
Using namespace std;

Class Bunch {
Enum { size =100};
Int i[size];
};

Int main()
{
Cout<<” sizeof (bunch) “<<sizeof(bunch)<<endl;
}
The use of enum here is guaranteed to occupy no storage in the object.
Enum { one =1, two =2, three };
The compiler will continue counting from the last value so the enumerator three will get the value 3


http://codepad.org/FFQR9O5A


Cosnt objects & member funciton
Class member function can be made const.

A const object is defined the same for a user defined type as a built in type.
Const int I =1;
Page no 359

Static variable inside the function
The storage for this object is not on the stack but instead in the program’s static
data area. This object is initialized only once the first time the function is called
and retain its value between function invocation

if you do not provide an initialize for a static variable of a built in type, the compiler guarantees that variable will be initialized to zero.
Static class objects inside function.The rules are the same for static objects of user-defined types, including the fact that some initialization is required for the object.

User defined types must be initialized with the constructor calls.
Using namespace std;

Class X {
Int I;
Public:
X(int ii =0) :i(ii) {} //default
~X() { cout<<” X:: ~X()”<<endl; }
};

Void f() {
Static X x1(47);

Static X x2; // default constructor required
}

Int main() {
F()
}

Deep copy Program
http://codepad.org/IFjgA6fd

Static object destructors
Destructor for static objects are called when main() exits or when the standard C library function exit() is explicitly called.

Controlling linkage
Any name at file scope is visible throughout all translation unit in a program This is often called external linkage Static is local to its translation unit. That names has internal linkage .This means
That you can use the same name in other translation unit without a name clash

One advantage to internal linkage is that the name can be placed in a header file
Without worrying that there will be clash at link time

Static VS global
If I declare in the file following function. It will represent two things

Int a=0;
The storage for a will be in the program’s static data area and the initialization
For a will occur once before main() entered. In the addition the visibility of a is global across all translation unit.

If it is
Static int a =0;
The variable a has internal linkage the storage class unchanged but scope is limited to file lavel

If it is
Using namespace std;
Int main()
{
Extern int I;
Std::cout << I;
}

In another file
Int I =5;

It is same like global function


Others storage class specifiers
Because C++ does not know much about your class, the default copy constructor and default assignment operators it provides use a copying method known as a shallow copy (also known as a memberwise copy).

A shallow copy means that C++ copies each member of the class individually using the assignment operator. When classes are simple (eg. do not contain any dynamically allocated memory), this works very well.

For example, let’s take a look at our Cents class

class Cents
{
private:
int m_nCents;

public:
Cents(int nCents=0)
{
m_nCents = nCents;
}
};

When C++ does a shallow copy of this class, it will copy m_nCents using the standard integer assignment operator. Since this is exactly what we’d be doing anyway if we wrote our own copy constructor or overloaded assignment operator, there’s really no reason to write our own version of these functions!


However, when designing classes that handle dynamically allocated memory, memberwise (shallow) copying can get us in a lot of trouble! This is because the standard pointer assignment operator just copies the address of the pointer — it does not allocate any memory or copy the contents being pointed to!

Let’s take a look at an example of this:

class MyString
{
private:
char *m_pchString;
int m_nLength;

public:
MyString(char *pchString="")
{
// Find the length of the string
// Plus one character for a terminator

m_nLength = strlen(pchString) + 1;
// Allocate a buffer equal to this length

m_pchString= new char[m_nLength];
// Copy the parameter into our internal buffer

strncpy(m_pchString, pchString, m_nLength);
// Make sure the string is terminated

m_pchString[m_nLength-1] = '\\0';
}


~MyString() // destructor
{
// We need to deallocate our buffer
delete[] m_pchString;
// Set m_pchString to null just in case
m_pchString = 0;
}

char* GetString() { return m_pchString; }

int GetLength() { return m_nLength; }

};


The above is a simple string class that allocates memory to hold a string that we pass in. Note that we have not defined a copy constructor or overloaded assignment operator. Consequently, C++ will provide a default copy constructor and default assignment operator that do a shallow copy.

Now, consider the following snippet of code:

MyString cHello("Hello, world!");
{
MyString cCopy = cHello; // use default copy constructor
} // cCopy goes out of scope here

std::cout << cHello.GetString() << std::endl; // this will crash

While this code looks harmless enough, it contains an insidious problem that will cause the program to crash! Can you spot it? Don’t worry if you can’t, it’s rather subtle.

Let’s break down this example line by line:

MyString cHello("Hello, world!");

This line is harmless enough. This calls the MyString constructor, which allocates some memory, sets cHello.m_pchString to point to it, and then copies the string “Hello, world!” into it

MyString cCopy = cHello; // use default copy constructor

This line seems harmless enough as well, but it’s actually the source of our problem! When this line is evaluated, C++ will use the default copy constructor (because we haven’t provided our own), which does a shallow pointer copy on cHello.m_pchString. Because a shallow pointer copy just copies the address of the pointer, the address of cHello.m_pchString is copied into cCopy.m_pchString. As a result, cCopy.m_pchString and cHello.m_pchString are now both pointing to the same piece of memory!

} // cCopy goes out of scope here

When cCopy goes out of scope, the MyString destructor is called on cCopy. The destructor deletes the dynamically allocated memory that both cCopy.m_pchString and cHello.m_pchString are pointing to! Consequently, by deleting cCopy, we’ve also (inadvertently) affected cHello. Note that the destructor will set cCopy.m_pchString to 0, but cHello.m_pchString will be left pointing to the deleted (invalid) memory!

std::cout << cHello.GetString() << std::endl;

Now you can see why this crashes. We deleted the string that cHello was pointing to, and now we are trying to print the value of memory that is no longer allocated.

The root of this problem is the shallow copy done by the copy constructor — doing a shallow copy on pointer values in a copy constructor or overloaded assignment operator is almost always asking for trouble.

Deep copying

The answer to this problem is to do a deep copy on any non-null pointers being copied. A deep copy duplicates the object or variable being pointed to so that the destination (the object being assigned to) receives it’s own local copy. This way, the destination can do whatever it wants to it’s local copy and the object that was copied from will not be affected. Doing deep copies requires that we write our own copy constructors and overloaded assignment operators.

Let’s go ahead and show how this is done for our MyString class:

// Copy constructor

MyString::MyString(const MyString& cSource)

{

// because m_nLength is not a pointer, we can shallow copy it
m_nLength = cSource.m_nLength;

// m_pchString is a pointer, so we need to deep copy it if it is non-null
if (cSource.m_pchString)
{
// allocate memory for our copy
m_pchString = new char[m_nLength];

// Copy the string into our newly allocated memory
strncpy(m_pchString, cSource.m_pchString, m_nLength);
}
else
m_pchString = 0;
}

As you can see, this is quite a bit more involved than a simple shallow copy! First, we have to check to make sure cSource even has a string (line 8). If it does, then we allocate enough memory to hold a copy of that string (line 11). Finally, we have to manually copy the string using strncpy() (line 14).

Now let’s do the overloaded assignment operator. The overloaded assignment operator is a tad bit trickier:


// Assignment operator

MyString& MyString::operator=(const MyString& cSource)
{
// check for self-assignment
if (this == &cSource)
return *this;

// first we need to deallocate any value that this string is holding!
delete[] m_pchString;
// because m_nLength is not a pointer, we can shallow copy it

m_nLength = cSource.m_nLength;
// now we need to deep copy m_pchString

if (cSource.m_pchString)
{
// allocate memory for our copy
m_pchString = new char[m_nLength];

// Copy the parameter the newly allocated memory
strncpy(m_pchString, cSource.m_pchString, m_nLength);
}
else
m_pchString = 0;

return *this;
}

Note that our assignment operator is very similar to our copy constructor, but there are three major differences:

We added a self-assignment check (line 5).
We return *this so we can chain the assignment operator (line 26).

We need to explicitly deallocate any value that the string is already holding (line 9).
When the overloaded assignment operator is called, the item being assigned to may already contain a previous value, which we need to make sure we clean up before we assign memory for new values. For non-dynamically allocated variables (which are a fixed size), we don’t have to bother because the new value just overwrite the old one. However, for dynamically allocated variables, we need to explicitly deallocate any old memory before we allocate any new memory. If we don’t, the code will not crash, but we will have a memory leak that will eat away our free memory every time we do an assignment!


Deep copy in my words
I wrote simple and get crash and did little bit analysis on this issue.


#include<iostream>
using namespace std;

class sample
{
  char *c_string;
  public:
  sample()
  {
        cout<<" the default constructor is "<<endl;
  }
  sample(char *p)
  {
      int i=0;
      while(p[i]!='\0')
             i++;

      c_string =new char[i+1];

      i=0;
      while(p[i]!='\0')
      {
             c_string[i]=p[i];
             i++;
      }

    char* getstring()
 {
     return c_string;
 }

 ~sample()
 {

    delete[] c_string;
  }
};

int main()
{
   sample c("hello");
   {
    sample copy =c; // want to write this line so i have put fix and find the program below
   }
   cout<<"The value of c"<<c.getstring()<<endl<<endl;
   return 0;
}


So I saw program crash i hope you have got understanding from the above article.

The value of c

*** glibc detected *** ./sh: double free or corruption (fasttop): 0x00000000154f1010 ***
======= Backtrace: =========
/lib64/libc.so.6[0x2add27eb82ef]
/lib64/libc.so.6(cfree+0x4b)[0x2add27eb873b]
./sh(__gxx_personality_v0+0x2dc)[0x400ac4]
./sh(__gxx_personality_v0+0x1e4)[0x4009cc]
/lib64/libc.so.6(__libc_start_main+0xf4)[0x2add27e63994]
./sh(__gxx_personality_v0+0x51)[0x400839]
======= Memory map: ========
00400000-00401000 r-xp 00000000 00:1a 1365237173                         /x/home-new/agoswami/my_work/sh
00601000-00602000 rw-p 00001000 00:1a 1365237173                         /x/home-new/agoswami/my_work/sh
154f1000-15512000 rw-p 154f1000 00:00 0                                  [heap]
2add27497000-2add274b3000 r-xp 00000000 fd:00 786434                     /lib64/ld-2.5.so
2add274b3000-2add274b5000 rw-p 2add274b3000 00:00 0
2add274c8000-2add274c9000 rw-p 2add274c8000 00:00 0
2add276b2000-2add276b3000 r--p 0001b000 fd:00 786434                     /lib64/ld-2.5.so
2add276b3000-2add276b4000 rw-p 0001c000 fd:00 786434                     /lib64/ld-2.5.so
2add276b4000-2add2779a000 r-xp 00000000 fd:00 1153587                    /usr/lib64/libstdc++.so.6.0.8
2add2779a000-2add27999000 ---p 000e6000 fd:00 1153587                    /usr/lib64/libstdc++.so.6.0.8
2add27999000-2add2799f000 r--p 000e5000 fd:00 1153587                    /usr/lib64/libstdc++.so.6.0.8
2add2799f000-2add279a2000 rw-p 000eb000 fd:00 1153587                    /usr/lib64/libstdc++.so.6.0.8
2add279a2000-2add279b4000 rw-p 2add279a2000 00:00 0
2add279b4000-2add27a36000 r-xp 00000000 fd:00 786449                     /lib64/libm-2.5.so
2add27a36000-2add27c35000 ---p 00082000 fd:00 786449                     /lib64/libm-2.5.so
2add27c35000-2add27c36000 r--p 00081000 fd:00 786449                     /lib64/libm-2.5.so
2add27c36000-2add27c37000 rw-p 00082000 fd:00 786449                     /lib64/libm-2.5.so
2add27c37000-2add27c44000 r-xp 00000000 fd:00 786486                     /lib64/libgcc_s-4.1.2-20080825.so.1
2add27c44000-2add27e44000 ---p 0000d000 fd:00 786486                     /lib64/libgcc_s-4.1.2-20080825.so.1
2add27e44000-2add27e45000 rw-p 0000d000 fd:00 786486                     /lib64/libgcc_s-4.1.2-20080825.so.1
2add27e45000-2add27e46000 rw-p 2add27e45000 00:00 0
2add27e46000-2add27f93000 r-xp 00000000 fd:00 786441                     /lib64/libc-2.5.so
2add27f93000-2add28193000 ---p 0014d000 fd:00 786441                     /lib64/libc-2.5.so
2add28193000-2add28197000 r--p 0014d000 fd:00 786441                     /lib64/libc-2.5.so
2add28197000-2add28198000 rw-p 00151000 fd:00 786441                     /lib64/libc-2.5.so
2add28198000-2add2819e000 rw-p 2add28198000 00:00 0
7fffac843000-7fffac858000 rw-p 7ffffffea000 00:00 0                      [stack]
ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0                  [vdso]
Aborted

sample(const sample& s)
  {

          int i=0;
          while(s.c_string[i]='\0')
                i++;

          c_string=new char[i+1];

          i=0;
          while(s.c_string[i]!='\0')
          {
                  c_string[i]=s.c_string[i];
                  i++;
          }
          c_string[i]='\0';
   }



so i  addes this function and able to write this line


but In main I want to write the below line.

sample d;
d=c;


than i have to write the following function.

char* operator=(const sample &s)
  {
          int  i=0;
          while(s.c_string[i]!='\0')
                   i++;

          c_string =new char[i+1];

          i=0;
          while(s.c_string[i]!='\0')
          {
                c_string[i] =s.c_string[i];
                i++;
           }
           c_string[i]='\0';
           return c_string;

   }