Tuesday, July 6, 2010

C++ FAQ

1. Stack Memory Vs Heap Memory
The heap


The heap (also known as the “free store”) is a large pool of memory used for dynamic allocation. In C++, when you use the new operator to allocate memory, this memory is assigned from the heap.
view source
print?

int *pValue = new int; // pValue is assigned 4 bytes from the heap
int *pArray = new int[10]; // pArray is assigned 40 bytes from the heap


Because the precise location of the memory allocated is not known in advance, the memory allocated has to be accessed indirectly — which is why new returns a pointer.

You do not have to worry about the mechanics behind the process of how free memory is located and allocated to the user. However, it is worth knowing that sequential memory requests may not result in sequential memory addresses being allocated!
view source

int *pValue1 = new int;
int *pValue2 = new int;
// pValue1 and pValue2 may not have sequential addresses

When a dynamically allocated variable is deleted, the memory is “returned” to the heap and can then be reassigned as future allocation requests are received.

The heap has advantages and disadvantages:

1) Allocated memory stays allocated until it is specifically deallocated (beware memory leaks).
2) Dynamically allocated memory must be accessed through a pointer.
3) Because the heap is a big pool of memory, large arrays, structures, or classes should be allocated here.


The stack

The call stack (usually referred to as “the stack”) has a much more interesting role to play. Before we talk about the call stack, which refers to a particular portion of memory, let’s talk about what a stack is.

Consider a stack of plates in a cafeteria. Because each plate is heavy and they are stacked, you can really only do one of three things:

1) Look at the surface of the top plate

2) Take the top plate off the stack

3) Put a new plate on top of the stack

In computer programming, a stack is a container that holds other variables (much like an array).

However, whereas an array lets you access and modify elements in any order you wish, a stack is more limited. The operations that can be performed on a stack are identical to the ones above:

1) Look at the top item on the stack (usually done via a function called top())

2) Take the top item off of the stack (done via a function called pop())

3) Put a new item on top of the stack (done via a function called push())

A stack is a last-in, first-out (LIFO) structure. The last item pushed onto the stack will be the first item popped off. If you put a new plate on top of the stack,

anybody who takes a plate from the stack will take the plate you just pushed on first. Last on, first off. As items are pushed onto a stack, the stack grows larger — as items are popped off, the stack grows smaller.

The plate analogy is a pretty good analogy as to how the call stack works, but we can actually make an even better analogy. Consider a bunch of mailboxes, all stacked on top of each other.

Each mailbox can only hold one item, and all mailboxes start out empty. Furthermore, each mailbox is nailed to the mailbox below it, so the number of mailboxes can not be changed. If we can’t change the number of mailboxes, how do we get a stack-like behavior?

First, we use a marker (like a post-it note) to keep track of where the bottom-most empty mailbox is.

In the beginning, this will be the lowest mailbox. When we push an item onto our mailbox stack, we put it in the mailbox that is marked (which is the first empty mailbox), and move the marker up one mailbox. When we pop an item off the stack, we move the marker down one mailbox and remove the item from that mailbox. Anything below the marker is considered “on the stack”. Anything at the marker or above the marker is not on the stack.

This is almost exactly analogous to how the call stack works. The call stack is a fixed-size chunk of sequential memory addresses. The mailboxes are memory addresses, and the “items” are pieces of data (typically either variables or addreses).


The “marker” is a register (a small piece of memory) in the CPU known as the stack pointer. The stack pointer keeps track of where the top of the stack currently is.

The only difference between our hypothetical mailbox stack and the call stack is that when we pop an item off the call stack, we don’t have to erase the memory (the equivalent of emptying the mailbox). We can just leave it to be overwritten by the next item pushed to that piece of memory. Because the stack pointer will be below that memory location, we know that memory location is not on the stack.

So what do we push onto our call stack? Parameters, local variables, and… function calls.

The stack in action

Because parameters and local variables essentially belong to a function, we really only need to consider what happens on the stack when we call a function. Here is the sequence of steps that takes place when a function is called:

1. The address of the instruction beyond the function call is pushed onto the stack. This is how the CPU remembers where to go after the function returns.

2. Room is made on the stack for the function’s return type. This is just a placeholder for now.

3. The CPU jumps to the function’s code.

4. The current top of the stack is held in a special pointer called the stack frame. Everything added to the stack after this point is considered “local” to the function.

5. All function arguments are placed on the stack.

6. The instructions inside of the function begin executing.

7. Local variables are pushed onto the stack as they are defined.

When the function terminates, the following steps happen:

1. The function’s return value is copied into the placeholder that was put on the stack for this purpose.

2. Everything after the stack frame pointer is popped off. This destroys all local variables and arguments.

3. The return value is popped off the stack and is assigned as the value of the function. If the value of the function isn’t assigned to anything, no assignment takes place, and the value is lost.

4. The address of the next instruction to execute is popped off the stack, and the CPU resumes execution at that instruction.

Typically, it is not important to know all the details about how the call stack works. However, understanding that functions are effectively pushed on the stack when they are called and popped off when they return gives you the fundamentals needed to understand recursion, as well as some other concepts that are useful when debugging.

Stack overflow

The stack has a limited size, and consequently can only hold a limited amount of information. I

If the program tries to put too much information on the stack, stack overflow will result.

Stack overflow happens when all the memory in the stack has been allocated — in that case, further allocations begin overflowing into other sections of memory.

Stack overflow is generally the result of allocating too many variables on the stack, and/or making too many nested function calls (where function A calls function B calls function C calls function D etc…) Overflowing the stack generally causes the program to crash.

Here is an example program that causes a stack overflow. You can run it on your system and watch it crash:

int main()
{
int nStack[100000000];
return 0;
}

This program tries to allocate a huge array on the stack. Because the stack is not large enough to handle this array, the array allocation overflows into portions of memory the program is not allowed to use. Consequently, the program crashes.

The stack has advantages and disadvantages:

Memory allocated on the stack stays in scope as long as it is on the stack. It is destroyed when it is popped off the stack.

All memory allocated on the stack is known at compile time. Consequently, this memory can be accessed directly through a variable.

Because the stack is relatively small, it is generally not a good idea to do anything that eats up lots of stack space. This includes allocating large arrays, structures, and classes, as well as heavy recursion.


Stack:

Stored in computer RAM like the heap.
Variables created on the stack will go out of scope and automatically deallocate.

Much faster to allocate in comparison to variables on the heap.

Implemented with an actual stack data structure.

Stores local data, return addresses, used for parameter passing

Can have a stack overflow when too much of the stack is used. (mostly from inifinite (or too much) recursion, very large allocations)

Data created on the stack can be used without pointers.


You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.

Usually has a maximum size already determined when your program starts

Heap:

Stored in computer RAM like the stack.

Variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[] or free

Slower to allocate in comparison to variables on the stack.

Used on demand to allocate a block of data for use by the program.

Can have fragmentation when there are a lot of allocations and deallocations

In C++ data created on the heap will be pointed to by pointers and allocated with new or malloc

Can have allocation failures if too big of a buffer is requested to be allocated.

You would use the heap if you don't know exactly how much data you will need at runtime or if you need to allocate a lot of data.

Responsible for memory leaks

Can you overload new operator

#include<iostream>
#include<malloc.h>

using namespace std;
class sample
{
 int i;
 char c;
 public:
 void* operator new(size_t s,int ii,char cc)
 {
  sample *q =(sample*) malloc(s);
 q->i =ii;
 q->c =cc;
 cout<<"Memory allocation"<<endl;
 return q;
 }
void operator delete(void *q)
 {
  free(q);
 }
 void display()
 {  cout<<i<<"   "<<c;
}
};

int main()
{
 sample *s =new (7,'a')sample;
 return 0;
}



when-do-you-overload-operator-new

What is mean of size_t and why we need it.

size_t is type of unsigned integer.which is the Return value of sizeof  operator.

`size_t' is a type suitable for representing the amount of memory a data object requires, expressed in units of `char'.
It is an integer type (C cannot keep track of fractions of a `char'), and it is unsigned (negative sizes make no sense). It is the type of the result of the `sizeof' operator. It is the type you pass to malloc() and friends to say how much memory you want. 

It is the type returned by strlen() to say how many "significant" characters are in a string.

Each implementation chooses a "real" type like `unsigned int' or `unsigned long' (or perhaps something else)

 to be its `size_t', depending on what makes the most sense. You don't  usually need to worry about what

`size_t' looks like "under the covers;" all you care about is that it is the "right" type for representing object sizes.

The implementation "publishes" its own choice of `size_t' in several of the Standard headers: <stdio.h>, <stdlib.h>, and some others. If you examine one of these headers (most implementations have some way of doing this), you are likely to find something like

#ifndef __SIZE_T
#define __SIZE_T
typedef unsigned int size_t;

#endif
.... meaning that on this particular implementation `size_t' is an `unsigned int'. Other implementations make other choices.

(The preprocessor stuff -- which needn't be in exactly the form  shown here -- ensures that your program will contain only one `typedef' for `size_t' even if it includes several of the headers that declare it)

The complexity of sorting algorithm


Pointers, arrays, and string literals



void strtoupper(char *str)



{


if (str) { // null ptr check, courtesy of Michael


while (*str != '\0') {


// destructively modify the contents at the current pointer location


// using the dereference operator to access the value at the current


// pointer address.


*str = toupper(*str);


++str;


}


}


}


my_str is actually a pointer to a block of memory holding chars. This allows us to use address math to access indices of the array and modify them using the dereference operator. In fact, an array index such as my_str[3] is identical to the expression *(my_str + 3).



char my_str[] = "hello world";

*my_str = toupper(*my_str);
*(my_str + 6) = toupper(*(my_str + 6));

printf("%s", my_str); // prints, "Hello World"



However, if my_str is declared as a char pointer to the string literal “hello world” rather than a char array, these operations fail:

char *my_str = "hello world";

*my_str = toupper(*my_str); // fails
*(my_str + 6) = toupper(*(my_str + 6)); // fails
printf("%s", my_str);


Let’s explore the difference between the two declarations.


char *a = "hello world";

char b[] = "hello world";
In the compiled program, it is likely that “hello world” is stored literally inside the executable. It is effectively an immutable, constant value. Pointing char *a to it provides the scope with read-only access to an immutable block of memory. Therefore, attempting to assign a value might cause other code that points to the same memory to behave erratically.

The declaration of char b[] instead declares a locally allocated block of memory that is then filled with the chars, “hello world”. b is now a pointer to the first address of that array. The complete statement, combining the declaration and assignment, is shorthand. Dispensing with the array size (e.g., char instead of char[12]) is permitted as the compiler is able to ascertain its size from the string literal it was assigned.


In both cases the pointer is used to access array indices:


int i;

for (i = 0; a[i] != '\0'; ++i)
printf("%c", toupper(a[i]));
However, only with b is the program able to modify the values in memory, since it is explicitly copied to a mutable location on the stack in its declaration:


int i;


for (i = 0; b[i] != '\0'; ++i)
b[i] = toupper(b[i]);
printf("%s", b);

Binary Search
A fast way to search a sorted array is to use a binary search. The idea is to look at the element in the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half.


Performance
The advantage of a binary search over a linear search is astounding for large numbers. For an array of a million elements, binary search, O(log N), will find the target element with a worst case of only 20 comparisons. Linear search, O(N), on average will take 500,000 comparisons to find the element. Probably the only faster kind of search uses hashing, a topic that isn't covered in these notes.


This performance comes at a price - the array must be sorted first. Because sorting isn't a fast operation, it may not be worth the effort to sort when there are only a few searches.

int main()


{


char my_str[] = "hello world";


strtoupper(my_str);


printf("%s", my_str);


return 0;


}


Boost  Libraries

The name should already give it away

A Smart Pointer is a C++ object that acts like a pointer, but additionally deletes the object when it is no longer needed.

No longer needed" is hard to define, since resource management in C++ is very complex. 
Different smart pointer implementations cover the most common scenarios

Many libraries provide smart pointer implementations with different advantages and drawbacks. The samples here use the BOOST library, a high quality open source template library, with many submissions considered for inclusion in the next C++ standard.

Boost provides the following smart pointer implementations:

shared_ptr<T>pointer to T" using a reference count to determine when the object is no longer needed. shared_ptr is the generic, most versatile smart pointer offered by boost.
scoped_ptr<T>a pointer automatically deleted when it goes out of scope. No assignment possible, but no performance penalties compared to "raw" pointers
intrusive_ptr<T>another reference counting pointer. It provides better performance than shared_ptr, but requires the type T to provide its own reference counting mechanism.
weak_ptr<T>a weak pointer, working in conjunction with shared_ptr to avoid circular references
shared_array<T>like shared_ptr, but access syntax is for an Array of T
scoped_array<T>like scoped_ptr, but access syntax is for an Array of T


The first: boost::scoped_ptr<T>

 scoped_ptr is the simplest smart pointer provided by boost. It guarantees automatic deletion when the pointer goes out of scope.

The samples use a helper class, CSample, that prints diagnostic messages when it it constructed,assigned, or destroyed

Still it might be interesting to step through with the debugger

The following sample uses a scoped_ptr for automatic destruction

Using normal pointersUsing scoped_ptr
Collapse


void Sample1_Plain()
{
  CSample * pSample(new CSample);

  if (!pSample->Query() )
  // just some function...

  {
    delete pSample;
    return;
  }

  pSample->Use();
  delete pSample;

}
Collapse
#include "boost/smart_ptr.h"


void Sample1_ScopedPtr()
{
  boost::scoped_ptr<CSample> 
             samplePtr(new CSample);

  if (!samplePtr->Query() )
  // just some function...

    return;    




  samplePtr->Use();

}

Using "normal" pointers, we must remember to delete it at every place we exit the function.

This is especially tiresome (and easily forgotten) when using exceptions.The second example uses a scoped_ptr for the same task.

It automatically deletes the pointer when the function eturns 8 even in the case of an exception thrown, which isn't even covered in the "raw pointer" sample!

The advantage is obvious: in a more complex function it's easy to forget to delete an object. 

scoped_ptr does it for you.Also, when dereferencing a NULL pointer, you get an assertion in debug mode.

use forautomatic deletion of local objects or class members1, Delayed Instantiation, implementing PIMPL and RAII (see below)
not good forelement in an STL container, multiple pointers to the same object
performance:scoped_ptr adds little (if any) overhead to a "plain" pointer, it performs

shared_ptr<T>

Reference counting pointers track how many pointers are referring to an object.and when the last pointer to an object is destroyed, it deletes the object itself, too.

 The "normal" reference counted pointer provided by boost is shared_ptr (the name indicates that multiple pointers can share the same object).

Let's look at a few examples:

void Sample2_Shared()
{
  // (A) create a new CSample instance with one reference

  boost::shared_ptr<CSample> mySample(new CSample); 
  printf("The Sample now has %i references\n", mySample.use_count()); // should be 1


  // (B) assign a second pointer to it:

  boost::shared_ptr<CSample> mySample2 = mySample; // should be 2 refs by now

  printf("The Sample now has %i references\n", mySample.use_count());

  // (C) set the first pointer to NULL

  mySample.reset(); 
  printf("The Sample now has %i references\n", mySample2.use_count());  // 1


  // the object allocated in (1) is deleted automatically

  // when mySample2 goes out of scope

}
 
Line (A) creates a new CSample instance on the heap, 
and assigns the pointer to a shared_ptr, mySample. Things look like this 
 
Then, we assign it to a second pointer mySample2. Now, two pointers access the same data:
 
We reset the first pointer (equivalent to p=NULL for a raw pointer).
The CSample instance is still there, since mySample2 holds a reference to it

Only when the last reference, mySample2, goes out of scope, the CSample is destroyed with it:
 
Of course, this is not limited to a single CSample instance, or two pointers, or a single function.
 
Here are some use cases for a shared_ptr.
 
use in containers 
using the pointer-to-implementation idiom (PIMPL) 
Resource-Acquisition-Is-Initialization (RAII) idiom 
Separating Interface from Implementation 

Important Features

The boost::shared_ptr implementation has some important features.

that make it stand out from other implementations

shared_ptr<T> works with an incomplete type

When declaring or using a shared_ptr<T>, T may be an "incomplete type"  

E.g., you do only a forward declaration using class T;

But do not yet define how T really looks like. 

shared_ptr<T> works with any type:

There are virtually no requirements towards T (such as deriving from a base class)

shared_ptr<T> supports a custom deleter

So you can store objects that need a different cleanup than delete p.For more information, see the boost documentation.

Implicit conversion:

If a type U * can be implicitly converted to T * (e.g., because T is base class of U), a shared_ptr<U> can also be converted to shared_ptr<T> implicitly.

shared_ptr is thread safe

(This is a design choice rather than an advantage, however, it is a necessity in multithreaded programs, and the overhead is low.)

 Example: Using shared_ptr in containers

Many container classes, including the STL containers, require copy operations
e.g., when inserting an existing element into a list vector, or container). However,
when this copy operations are expensive (or are even unavailable),

the typical solution is to use a container of pointers

std::vector<CMyLargeClass *> vec;
vec.push_back( new CMyLargeClass("bigString") );

However, this throws the task of memory management back to the caller
We can, however, use a shared_ptr

typedef boost::shared_ptr<CMyLargeClass>  CMyLargeClassPtr;
std::vector<CMyLargeClassPtr> vec;
vec.push_back( CMyLargeClassPtr(new CMyLargeClass("bigString")) );


Very similar, but now, the elements get destroyed automatically when
the vector is destroyed

unless, of course, there's another smart pointer still holding a reference Let's have a look at sample

void Sample3_Container()
{
  typedef boost::shared_ptr<CSample> CSamplePtr;

  //
(A) create a container of CSample pointers:  std::vector<CSamplePtr> vec;

  //
(B) add three elements  vec.push_back(CSamplePtr(new CSample));
  vec.push_back(CSamplePtr(new CSample));
  vec.push_back(CSamplePtr(new CSample));

  //
(C) "keep" a pointer to the second:   CSamplePtr anElement = vec[1];

  //
(D) destroy the vector:  vec.clear();

  //
(E) the second element still exists  anElement->Use();
  printf("done. cleanup is automatic\n");

  //
(F) anElement goes out of scope, deleting the last CSample instance}

A few things can go wrong with smart pointers  most prominent is an invalid reference count
which deletes the object too early, or not at all

The boost implementation promotes safety, making all "potentially dangerous" operations explicit. So, with a few rules to remember, you are safe

Rule 1: Assign and keep
Assign a newly constructed instance to a smart pointer immediately and then keep it there The smart pointer(s) now own the object, you must not delete it manually, nor can you take it away again This helps to not accidentally delete an object that is still
 referenced by a smart pointer, or end up with an invalid reference count.

Rule 2 : 
a _ptr<T> is not a T * - more correctly, there are no implicit conversions between
 a T * and a smart pointer to type T

This means:

When creating a smart pointer, you explicitly have to write ..._ptr<T> myPtr(new T)

You cannot assign a T * to a smart pointer

You cannot even write ptr=NULL. Use ptr.reset() for that

To retrieve the raw pointer, use ptr.get(). Of course, you must not delete this pointer or use it after the smart pointer it comes from is destroyed
reset or reassigned
Use get() only when you have to pass the pointer to a function that expects a raw pointer

You cannot pass a T * to a function that expects a _ptr<T> directly.
You have to construct a smart pointer explicitly, which also makes it
clear that you transfer ownership of the raw pointer to the smart pointer. (See also Rule 3.)

Rule 2: No circular references
If you have two objects referencing each other through a reference counting pointer
they are never deleted. boost provides weak_ptr to break such cycles (see below).

Rule 3: no temporary shared_ptr
Do not construct temporary shared_ptr to pass them to functions,
always use a named (local) variable.


Cyclic References
Reference counting is a convenient resource management mechanism, it has one fundamental drawback though:

Reference counting is a convenient resource management mechanism, it has one fundamental drawback though:

struct CDad; struct CChild;

typedef boost::shared_ptr<CDad>   CDadPtr;
typedef boost::shared_ptr<CChild> CChildPtr;


struct CDad : public CSample
{
   CChildPtr myBoy;
};

struct CChild : public CSample
{
  CDadPtr myDad;
};
// a "thing" that holds a smart pointer to another "thing":
CDadPtr   parent(new CDadPtr);
CChildPtr child(new CChildPtr);

// deliberately create a circular reference:parent->myBoy = child;
child->myDad = dad;


Some Useful url related C++ FAQ

http://www.daniweb.com/forums/thread107723.html


// resetting one ptr...child.reset();

parent still references the CDad object, which itself references the CChild. The whole thing looks like this:

If we now call dad.reset(), we lose all "contact" with the two objects.
But this leaves both with exactly one reference, and the shared pointers 
see no reason to delete either of them! We have no access to them anymore but they mutually keep themselves "alive".

This is a memory leak at best; in the worst case, the objects hold even more critical resources
that are not released correctly.

The problem is not solvable with a "better" shared pointer implementation
or at least, only with unacceptable overhead and restrictions
So you have to break that cycle. There are two ways:

Manually break the cycle before you release your last reference to it
When the lifetime of Dad is known to exceed the lifetime of Child, the
child can use a normal (raw) pointer to Dad.

Use a boost::weak_ptr to break the cycle

Solutions (1) and (2) are no perfect solutions but they work with smart pointer libraries that do not offer a weak_ptr like boost does







 



 

 

 

  

 

 

 

 

 

 

 

 





Tuesday, June 22, 2010

C++ Program list (link list)

1. Create SimPle link list with some operation
#include
using namespace std;


class node
{
public:
T data;
node *next;
};
template <class T>
class link
{

public:
node *first;
link();
void add_node(T data);
void create_link_list();
void insert_data_link_list(T data);
void add_node_link_list(T data);
void delete_node_after_data_node(T data);
void delete_node_before_data_node(T data);
friend ostream& operator<< (ostream &o ,link &link_lst);

};
template<class T>
link::link()
{
first =NULL;
}

//Create node in link list
template
void link::add_node(T data)
{

node *last;
node *p =new node;
//filling data
p->data =data;
p->next =NULL;

if(first==NULL)
first=p;

else
{
   last=first;
   while(last->next!=NULL)
   last =last->next;
   last->next =p;
}

}

// Provide the input and create the link list.
template<class T>
void link::create_link_list()
{

node *p =new node;
T data;
node *last;
if(first == NULL)
{
cout<<"Enter the data"<<data<<endl;

p->data =data;
p->next =NULL;

first =p;
}

int continue_list =1;
while(continue_list)
{
    cout<<"Enter data "<<data;
    add_node(data);
      cout<<" Do you want to continue Please enter 1 or 0"<<endl;
 }

}

//Insert data into Link list
//Ex  1->2->3
//output : 1->11->2->11->3
template <class T>
void link::insert_data_link_list(T data)
{

node *last =first;

while(last->next!=NULL)
{
   node *p =new node;
   p->data =data;
   p->next =last->next;
  last->next =p;
  last = p->next;
 }
}

// Add Node before Node into Link list
template<class T>
void link::add_node_link_list(T data)
{

    node *last;
   //if the list is empty
   if(first->next == NULL)
   {
        node *p =new node;
        p->data =data;
        p->next =first;
        first =p;
   }
while(last->next!=NULL)
{
    node *p =new node;
    p->data =data;
    p->next =last->next;
    last->next =p;
    last=p->next;
}
}

//Delete the Node After Data found
template<class T>
void link::delete_node_after_data_node(T data)
{
node *last;
if(first->data =data &&  first->next ==NULL)
{
cerr<<"you have only one node"<<endl;
}
else
{
      last=first;
      while(last->next!=NULL)
      {
                 if(last->data ==data)
                    {
                         p = last->next;
                        last->next = p->next;
                        delete p;
                    }
               last =last->next;
          }
 }

}
//Delete the Node Before Data found
template
void link::delete_node_before_data_node(T data)
{

      node *last;

      if(first->data =data && first->next == NULL)
     {
         cerr<<"you have only one node"<<endl;
     }
    else if (first->next->data == data)
    {
              p=first->next;
              first=p;
             delete first;
     }
else
{
 last =first;
while(last->next !=NULL)
{
if(last->next->next->data =data)
{
       p=last->next;
      last->next = p->next;
      delete p;
 }
last= last->next;
}
}
}

// Print the link list
template<class T>
ostream& operator<< <T>(ostream &o, link &link_list)
{
       node *last =link_list.first;
       while(last !=NULL)
      {
             o<<last->data<<endl;
             last=last->next;
      }
 last =last->next;
}
return o;
}

2. Add two singly link list


#include <iostream.h>

template<class T> 
class node
{
   public:
  T data;
   node *next;
};


template<class T>
class link
{
   public:
   node *first;
   link();
   void operator+(link& b);
};

template <class T>
link::link()
{
first =NULL;
}

//Add two link list
template <class T>
void link::operator + (link &b)
{

node *last =first;
while(last-&gt;next!=NULL)
last =last-&gt;next;

node *second_last = b.first;
last->next =second_last;

while(second_last->next!=NULL)
second_last =second_last->next;

}

int main()
{
   a.operator+(b);
}

#Swap the data of Node

#include<iostream>
using namespace std;

template<class T>
class node
{
 public:
 T data;
  node *next;
};

template<class T>
class link_list
{

 public:
 node<T> *first;
 link_list();
 void create_link_list(T data);
 void swap_node_data();
 friend ostream& operator<< <T>(ostream &o,link_list<T>& link);
};

template<class T>
link_list<T>::link_list()
{
 first =NULL;
}

//Create Node in the link list
template<class T>
void link_list<T>::create_link_list(T data)
{
 node<T> *last;
 node<T> *p =new node<T>;
 p->data =data;
 p->next =NULL;

 if(first ==NULL)
 {
    first =p;
  }
 else
{
  last =first;
  while(last->next!=NULL)
   last =last->next;
  last->next =p;
 }
}

//swap the data
template<class T>
void link_list<T>::swap_node_data()
{
 node<T> *last =first;
 node<T> *p;

 while(last ->next->next !=NULL)
 {
   int no =last->data;
   last->data =last->next->data;
  last->next->data =no;
  last =last->next->next;
}
}

template<class T>
ostream& operator<<(ostream& o,link_list<T>& link)
{
 node<T> *last = link.first;
 while(last!=NULL)
 {
  o<<last->data<<" ------>" ;
  last =last->next;
 }
 return o;
}

int main()
{
 link_list<int>a;

 for(int i=0;i<6;i++)
 {
  a.create_link_list(i);
 }
 cout<<a;
 cout<<endl<<endl;
 a.swap_node_data();

 cout<<a;
 return 0;
}


Overload New Operator Program
#include<iostream>
#include<malloc.h>

using namespace std;
class sample
{
     int i;
     char c;
    public:
    void* operator new(size_t s,int ii,char cc)
   {
        sample *q =(sample*) malloc(s);
        q->i =ii;
        q->c =cc;
       cout<<"Memory allocation"<<endl;
       return q;
    }
void operator delete(void *q)
 {
  free(q);
 }
 void display()
 {
  cout<<i<<"   "<<c;
 }
};

int main()
{
 sample *s =new (7,'a')sample;
 return 0;
}


6.   1-------->2------->3------->4-------->5



         \    /     \  /        \  /       \  /


           3         -1         7          -1




#include<iostream>
using namespace std;

template<class T>
class node
{
 public:
 T data;
  node<T> *next;
};

template<class T>
class link_list
{
 public:
 node<T> *first;
 link_list();
 void create_link_list(T data);
 void new_link_list();
 friend ostream& operator<< <T>(ostream &o,link_list<T> &link);
};

template<class T>
link_list<T>::link_list()
{
 first =NULL;
}
template<class T>
void link_list<T>::create_link_list( T data)
{
 node<T> *last;
 node<T> *p =new node<T>;
 p->data =data;
 p->next =NULL;

 if(first ==NULL)
 {
  first =p;
 }
 else
 {
  last =first;
  while(last->next!=NULL)
   last =last->next;
  last->next =p;
 }
}

template<class T>
void link_list<T>::new_link_list()
{
 node<T> *last =first;
 node<T> *t =first;
 while(last->next!=NULL)
 {
  node<T> *p =new node<T>;
  p->data =last->data +last->next->data;
  last =last->next;
  p->next =t->next;
  t->next =p;
  t=last;
 // cerr<<"last"<<last->data<<endl;
  node<T> *s =new node<T>;

  s->data = last->data - last->next->data;
  last =last->next;
  s->next =t->next;
  t->next =s;
  t =last;
 }
}
template<class T>
ostream& operator<< ( ostream& o,link_list<T>&list)
{
 node<T> *last =list.first;
 while(last!=NULL)
 {
  o<< last->data <<"   ----->";
  last =last->next;
 }
}

int main()
{
 link_list<int> a;
 for(int i=0;i<5;i++)
  a.create_link_list(i);
 cout<<a;

 a.new_link_list();
 cout<<a;
 return 0;
}


1------->2------>3-------->4--------->5


                   \/ \/                 \/  \/


                   3  -1                7  -1






#include<iostream>
using namespace std;

template<class T>
class node
{
  public:
 T data;
 node<T> *next;
};

template<class T>
class link_list
{
 public:
 link_list();
 void create_link_list(T data);
 void new_link_list();
 friend ostream& operator<< <T>(ostream &o,link_list<T>&link);
 node<T> *first;
};

template<class T>
link_list<T>::link_list()
{
 first =NULL;
}

template<class T>
void link_list<T>::create_link_list(T data)
{
node<T> *last;
node<T> *p =new node<T>;

 p->data =data;
 p->next =NULL;
 if(first ==NULL)
 {
  first =p;
 }
 else
 {
  last =first;
  while(last->next!=NULL)
   last=last->next;

  last->next=p;
 }
}

template<class T>
ostream& operator<< (ostream& o,link_list<T>& link)
{
 node<T> *last =link.first;
 while(last!=NULL)
 {
  o<<last->data<<" --->";
  last =last->next;
 }

}

template<class T>
void link_list<T>::new_link_list()
{
 node<T> *last =first;
 node<T> *a  =first;

// node<T> *b =first;

 while(last->next!=NULL)
 {
  node<T> *p =new node<T>;
  node<T> *s =new node<T>;


  p->data =last->data +last->next->data;
  s->data =last->data -last->next->data;

  last =last->next;
  a= last;

 last =last->next;
 p->next =a->next;
 a->next =p;

 // b=a->next;
  s->next =p->next;
  p->next =s;
 }
}

int main()
{
 link_list<int> a;
 for(int i=1;i<=5;i++)
 a.create_link_list(i);
 cout<<a;
 cerr<<endl<<endl;
 a.new_link_list();
 cout<<endl;
 cout<<a;
}




1---->2---->3----->-1------->3----->4----->7---->-1----->5


To remove the same node in the singly link list

#include<iostream>
using namespace std;

template<class T>
class node
{
 public:
 T data;
 node<T> *next;

};

template<class T>
class link_list
{
 public:
 link_list();
 void create_link_list(T data);
 void new_link_list();
 friend ostream& operator<< <T>(ostream &o,link_list<T> &link);
 node<T> *first;
};

template<class T>
link_list<T>::link_list()
{
 first =NULL;
}
template<class T>
void link_list<T>::create_link_list(T data)
{
 node<T> *last;
 node<T> *p =new node<T>;
 p->data =data;
 p->next =NULL;

 if(first ==NULL)
    first =p;
 else
 {
  last =first;
  while(last->next!=NULL)
   last=last->next;
  last->next =p;
 }
}

template<class T>
ostream& operator << ( ostream &o,link_list<T> &link)
{
 node<T> *last =link.first;
 while(last!=NULL)
 {
  o<<last->data<<"  ----->";
  last =last->next;
 }
}

template<class T>
void link_list<T>::new_link_list()
{
 node<T> *last=first;
 node<T> *q;
 while(last->next!=NULL)
 {
  node<T> *second =last->next;
 node<T> *p =last;

  while(second->next!=NULL)
 {
   cerr<<" second->data "<<second->data<<endl;
   if(last->data != second->data)
  {
    second =second->next;
    p =p->next;
   }

   else
   {
          q=p->next;
          p->next =q->next;
          delete q;
          second = p->next;
   }
}
      last =last->next;
 }

}

int main()
{
 link_list<int>a;
 for(int i=0;i<5;i++)
 {
  int data;
 cout<<" enter data"<<endl;
  cin>>data;
  a.create_link_list(data);
 }

 cout<<a;
 a.new_link_list();
 cout<<a;
}


can you make stack with singly link list
#include<iostream>
using namespace std;

template<class T>
class node
{

 public:
 T data;
 node<T> *next;
};
template<class T>
class stack
{

 public:
 node<T> *top;
 stack();

 void push(T data);
 int pop();
 friend ostream& operator<< <T>(ostream& o,stack<T>& stack);

};

template<class T>
stack<T>::stack()
{
 top =NULL;
}

template<class T>
void stack<T>::push(T data)
{

 node<T> *p =new node<T>;
 p->data =data;
 p->next =NULL;

 if(top ==NULL)
 {
      top =p;
 }
 else
 {
  p->next =top;
  top =p;
 }
}

template<class T>
int stack<T>::pop()
{
 node<T> *p;
 if(top ==NULL)
 cout<<"stack is empty"<<endl;
else
 {
  p=top;
  top =top->next;
  return p->no;
 }

}

template<class T>
ostream& operator<< (ostream&o, stack<T>&a)
{
 node<T> *last =a.top;
 cout<<last->data<<"   ---->";
}

int main()
{
   stack<int> a;
   for(int i=0;i<5;i++)
   a.push(i);
   cout<<a;
}
can you make queue with single link list

#include<iostream>
using namespace std;
template<class T>
class node
{
 public:
 T data;
 node<T> *next;
};

template<class T>
class queue
{
 public:
 node<T> *front;
 node<T> *rear;
 queue();

 void add(T data);
 int remove();
 friend ostream& operator<< <T>(ostream&a,queue<T>& qu);
};

template<class T>
queue<T>::queue()
{
 front =NULL;
 rear =NULL;
}

template<class T>
void queue<T>::add(T data)
{
 node<T> *p =new node<T>;
 p->data =data;
 p->next =NULL;

 if(rear==NULL)
    front=rear=p;

 else
 {
  rear->next=p;
  rear=rear->next;
 }
}

template<class T>
int queue<T>::remove()
{

 if(front==NULL)
   cout<<"queue is empty"<<endl;
 else
 {
     p=front;
     if(front->next!=NULL)
  front=front->next;
  return p->no;

 }
}
template<class T>
ostream& operator<< (ostream& o,queue<T>&q)
{
     node<T>* last =q.rear;
     while(last!=q.front)
    {
      o<<q.front->data;
      q.front =q.front->next;
   }
}

int main()
{
 queue<int>a;
  for(int i=0;i<5;i++)
 a.add(i);
 cout<<a;
}

Encrypt & decrypt Program
#include<iostream>
#include<string>

using namespace std;
class enc
{

public:
void getstring();
void encrypt();
void decrypt();
void show();

string s;
};


void enc::getstring()
{
cout<<"enter the string "<<endl;
cin>>s;
}

void enc::encrypt()
{
int i=0;
while(s[i]!='\0')
{
s[i] =s[i]+1;
i++;
}
}

void enc::decrypt()
{
int i=0;
while(s[i]!='\0')
{
s[i]=s[i]-1;
i++;
}
}

void enc::show()
{
cout<<s;
}

int main()
{
enc c;
c.getstring();
c.encrypt();
c.show();
c.decrypt();
c.show();
return 0;
}

The Program for 2^n

/*


* The Program for 2^n with the help

* of shift operator */

#include<iostream>
using namespace std;

int main()
{
int base;
int power;

cout<<" enter the base number"<<endl;
cin>>base;

cout<<" enter the power of number"<<endl;
cin>>power;

for(int i=0;i<power-1;i++)
base =base<<1;

cout<<base;
return 0;
}

To count the number of character & tabs blanks

/*



* To count the number of character & tabs blanks


* */


#include<iostream>
#include<fstream>
using namespace std;

int main()
{
FILE *fp;
char ch;
int nob=0;
int noc=0;
int nol=0;

fp=fopen("abhi.txt","r");
while(1)
{
ch=fgetc(fp); //to get character
if(ch ==EOF)
noc++;
if(ch==' ')
nob++;
if(ch=='\n')
nol++;
}
fclose(fp);

cout<<"number of character "<<noc<<endl;
cout<<"number of blank space "<<nob<<endl;
cout<<"number of line"<<nol<<endl;
return 0;
}

Print the top two element of stack

/*


* Print the top two element of stack

* */

#include<iostream>
#define size 5
using namespace std;

template<class T>
class stack
{
int pos;
public:
void push(T data);
T pop();
stack();
void show();
T stack_size[size];
};

template<class T>
stack<T>::stack()
{
pos=-1;
for(int i=0;i<5;i++)
stack_size[i]=0;
};
template<class T>
void stack<T>::push(T data)
{
stack_size[++pos]= data;
}
template<class T>
T stack<T>::pop()
{
return stack_size[pos--];
}

template<class T>
void stack<T>::show()
{
cout<<"showing top two element of stack"<<endl;
cout<<stack_size[pos]<<" " <<stack_size[pos-1]<<endl;
cout<<endl<<endl;
}

int main()
{
stack<int> s;
for(int j=0;j<5;j++)
s.push(j);
s.show();
return 0;
}





C++ Question & answer


What is heap.
The stack is a place in the computer memory where all the variables that are declared and initialized before runtime are stored. The heap is the section of computer memory where all the variables created or initialized at runtime are stored.
What are the memory segments?
The distinction between stack and heap relates to programming. When you look at your computer memory, it is organized into three segments:
text (code) segment
stack segment
heap segment
The text segment (often called code segment) is where the compiled code of the program itself resides. When you open some EXE file in Notepad, you can see that it includes a lot of "Gibberish" language, something that is not readable to human. It is the machine code, the computer representation of the program instructions. This includes all user defined as well as system functions.
What is stack?
The two sections other from the code segment in the memory are used for data. The stack is the section of memory that is allocated for automatic variables within functions.
Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is a section of memory and its associated registers that is used for temporary storage of information in which the most recently stored item is the first to be retrieved.
What is heap?
On the other hand, heap is an area of memory used for dynamic memory allocation. Blocks of memory are allocated and freed in this case in an arbitrary order. The pattern of allocation and size of blocks is not known until run time. Heap is usually being used by a program for many different purposes.
The stack is much faster than the heap but also smaller and more expensive.

When can you tell that a memory leak will occur?
A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory.
Memory leak is - dynamically allocating memory and forgeting to free it. In C++, using a new operator to allocate a chunk of memory, and forgetting to delete it. There are several reasons this could occur. Some of them are,
1. Allocate a chunk of memory and assign the starting address to a pointer variable, and later, reassing another address to the same pointer without freeing its original address
2. Allocate memory for an array and not using proper delete method (delete[]) to free the memory
3. Unhandled exceptions - allocating memory and deleting it at the end of the program, but the program abnormally terminates (crashes) before the delete code line is executed.

Some of the ways of avoiding memory leaks within a class object are
1. Allocate all dynamic memory required for the class in the constructor, and delete it in the distructor
2. Use TRY/CATCH blocks around all statements where there is a possiblity of a crash
3. Override new operator for your class and Track memory allocations and pointers. Override delete operator and untrack the deleted/freed memory.
In the destructor, check to see if there are any tracked memory locations (not freed) and free them up.

But beyond all these, it's still a good programming style that avoids memory leaks, because beyond objects, there is a program where you instantiate and run these objects. If you are allocating memory dynamically in the parent program, then carefully make sure you delete those chunks at all exit points (or centralize your exit point).


What is binary tree?

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.

What is a node class?

A node class is a class that,
► relies on the base class for services and implementation,
► provides a wider interface to the users than its base class,
► relies primarily on virtual functions in its public interface
► depends on all its direct and indirect base class
► can be understood only in the context of the base class
► can be used as base for further derivation
► can be used to create objects.A node class is a class that has added new services or functionality beyond the services inherited from its base class.

What is impact of signed numbers on the memory

Sign of the number is the first bit of the storage allocated for that number. So you get one bit less for storing the number. For example if you are storing an 8-bit number, without sign, the range is 0-255. If you decide to store sign you get 7 bits for the number plus one bit for the sign. So the range is -128 to +127.

What is Linked List ?

Linked List is one of the fundamental data structures. It consists of a sequence of? nodes,each containing arbitrary data fields and one or two (?links?) pointing to the next and/or previous nodes.A linked list is a self-referential datatype because it contains a pointer or link to another data of the same type.Linked lists permit insertion and removal of nodes at any point in the list in constant time, but do not allow random access

What is the data structures used to perform recursion?

Stack. Because of its LIFO (Last In First Out) property it remembers its caller so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, stack is to be used.

What are the major data structures used in the following areas :
RDBMS, Network data model & Hierarchical data model?


1.RDBMS Array (i.e. Array of structures)
2. Network data model Graph
3. Hierarchical data model Trees.

What is precision?

Precision refers the accuracy of the decimal portion of a value. Precision is the number of digits allowed after the decimal point.

Why do we Use a Multidimensional Array?

A multidimensional array can be useful to organize subgroups of data within an array.
In addition to organizing data stored in elements of an array, a multidimensional array can store memory addresses of data in a pointer array and an array of pointers.
Multidimensional arrays are used to store information in a matrix form.e.g. a railway timetable, schedule cannot be stored as a single dimensional array.
One can use a 3-D array for storing height, width and length of each room on each floor of a building.

Is Pointer a variable?

Yes, a pointer is a variable and can be used as an element of a structure and as an attribute of a class in some programming languages such as C++, but not Java.

However, the contents of a pointer is a memory address of another location of memory, which is usually the memory address of another variable, element of a structure, or attribute of a class.

How many parts are there in a declaration statement?

There are two main parts, variable identifier and data type and the third type is optional which is type qualifier like signed/unsigned.

What is placement new?


Operator new allocates memory from the heap, on which an object is constructed.

Standard C++ also supports placement new operator, which constructs an object on a pre-allocated buffer.
This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-allocated buffer takes less time)

void placement() {

char *buf = new char[1000]; //pre-allocated buffer
string *p = new (buf) string("hi"); //placement new
string *q = new string("hi"); //ordinary heap allocation

}

If you are using C language to implement the heterogeneous linked list, what pointer type will you use?


The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.

What is the difference between NULL AND VOID pointer?

NULL can be value for pointer type variables.VOID is a type identifier which has not size.NULL and void are not same. Example: void* ptr = NULL;

Define Simulation

Simulation is the process of forming an abstract model from a real situation in order to understand the impact of modifications and the effect of introducing various strategies on the situation.


What is a spanning Tree?


A spanning tree of a graph is just a subgraph that contains all the vertices and is a tree.
What is the quickest sorting method to use?

The answer depends on what you mean by quickest.
For most sorting problems, it just doesn't matter how quick the sort is because it is done infrequently or other operations take significantly more time anyway.

Even in cases in which sorting speed is of the essence, there is no one answer. It depends on not only the size and nature of the data, but also the likely order. No algorithm is best in all cases.

There are three sorting methods in this author's toolbox that are all very fast and that are useful in different situations. Those methods are quick sort, merge sort, and radix sort.
The Quick SortThe quick sort algorithm is of the divide and conquer type. That means it works by reducing a sorting problem into several easier sorting problems and solving each of them. A dividing value is chosen from the input data, and the data is partitioned into three sets: elements that belong before the dividing value, the value itself, and elements that come after the dividing value. The partitioning is performed by exchanging elements that are in the first set but belong in the third with elements that are in the third set but belong in the first Elements that are equal to the dividing element can be put in any of the three sets the algorithm will still work properly.

The Merge SortThe merge sort is a divide and conquer sort as well. It works by considering the data to be sorted as a sequence of already-sorted lists (in the worst case, each list is one element long). Adjacent sorted lists are merged into larger sorted lists until there is a single sorted list containing all the elements. The merge sort is good at sorting lists and other data structures that are not in arrays, and it can be used to sort things that don't fit into memory. It also can be implemented as a stable sort.
The Radix SortThe radix sort takes a list of integers and puts each element on a smaller list, depending on the value of its least significant byte. Then the small lists are concatenated, and the process is repeated for each more significant byte until the list is sorted. The radix sort is simpler to implement on fixed-length data such as int.

What is a priority queue?

A priority queue is an abstract data type in computer programming that supports the following three operations:
insertWithPriority: add an element to the queue with an associated priority
getNext: remove the element from the queue that has the highest priority, and return it (also known as "PopElement(Off)", or "GetMinimum")
peekAtNext (optional): look at the element with highest priority without removing it

What is a one way chain or singly linked linear list?

A list has been defined to consist of an ordered set of elements which may vary in number. A simple way to represent a linear list is to expand each node to contain a link or pointer to the next time.

In RDBMS, what is the efficient data structure used in the internal storage representation?

B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes.

What is virtual constructors/destructors?

Although C++ provides a default destructor for your classes if you do not provide one yourself, it is sometimes the case that you will want to provide your own destructor (particularly if the class needs to deallocate memory).

You should always make your destructors virtual
if you’re dealing with inheritance. Consider the following example.

class Base
{
public:
~Base()
{
cout << "Calling ~Base()" << m_pnarray =" new" pderived =" new" pbase =" new">

Because pBase is a Base pointer, when pBase is deleted, the program looks to see if the Base destructor is virtual. It’s not, so it assumes it only needs to call the Base destructor. We can see this in the fact that the above example :

prints.Calling ~Base()



http://www.geekinterview.com/question_details/19709



Why can't we overload the sizeof, :?, :: ., .* operators in c++?
Most operators can be overloaded by a programmer. The exceptions are
. (dot) :: ?: sizeof
There is no fundamental reason to disallow overloading of ?:. I just didn't see the need to introduce the special case of overloading a ternary operator. Note that a function overloading expr1?expr2:expr3 would not be able to guarantee that only one of expr2 and expr3 was executed.
Sizeof cannot be overloaded because built-in operations, such as incrementing a pointer into an array implicitly depends on it. Consider:
X a[10];
X* p = &a[3];
X* q = &a[3];
p++; // p points to a[4]
// thus the integer value of p must be
// sizeof(X) larger than the integer value of q


Thus, sizeof(X) could not be given a new and different meaning by the programmer without violating basic language rules.

In N::m neither N nor m are expressions with values; N and m are names known to the compiler and :: performs a (compile time) scope resolution rather than an expression evaluation. One could imagine allowing overloading of x::y where x is an object rather than a namespace or a class, but that would - contrary to first appearances - involve introducing new syntax (to allow expr::expr). It is not obvious what benefits such a complication would bring.
Operator . (dot) could in principle be overloaded using the same technique as used for ->. However, doing so can lead to questions about whether an operation is meant for the object overloading . or an object referred to by . For example:
class Y {
public:
void f();
// ...
};

class X { // assume that you can overload .
Y* p;
Y& operator.() { return *p; }
void f();
// ...
};

void g(X& x)
{
x.f(); // X::f or Y::f or error?
}


what are the disadvantages of copy constructor?

Well if we are talking about the default copy constructor, then the disadvantage it suffers from is that i does a shallow copy of the class object. Which means that if the class has some dynamic memory allocated or file pointers, the copied object will also point to the same memory location or files. That is the memory or file is not copied

What is namespace?

A namespace defines an area of code in which all identifiers are guaranteed to be unique. By default, all variables and functions are defined in the global namespace. For example, take a look at the following snippet:

int nX = 5;
int foo(int nX){
return -nX;}



What is encapsulation?

Encapsulation is the idea of hiding the details of how something is implemented and instead exposing an interface to the user. This allows the user to use the item without having to worry about how it is implemented.

What is function overriding?

function overriding is one in which functions have the same name and same number,type of arguments.. its only the implementations that differs.. they are accessed based on the object of the class being called 




Final class
 

To make the class final, the first solution that comes in mind is to make its constructor private, and make a static function to create the objects.
But there is one problem in this approach that there may be more than one constructor in the class and you have to make all of them private.
There is still a chance that anyone can make another public constructor.
A quick fix to this problem is to make the destructor private instead of making a constructor because there can be only one destructor in the class.

class FinalClass
{
private:
~FinalClass()
{ }
public:
static FinalClass* CreateInstance()
{ return new FinalClass; }. . .
};
The one problem with this approach is that
the creation of an object is not possible on the stack;

So I have added some piece of code for checking error if we create any object in stack.


int main()
{
    FinalClass a;  // end up with error, destructor is private
   FinalClass *d = FinalClass :: CreateInstance();
  //This is only way we can create object

                                                

 

the object must be created on the heap. And now it is the responsibility of the user of this class to destroy this object. Again, in this case there is a chance of a memory leak if the user of this class forgets to delete the object of this class from the heap when it is not needed.

Let's take a look at another approach of making a class final and still make it in such a way that the client of this class can create its object on the stack, not only on the heap. We all know that when we make one class a friend of another, it
can create an object of that class even its destructor is private. So, we can create one temporary class and make its constructor private. We also can inherit one class from it and make the drive class a friend of its base class because if we didn't do it, we can't inherit the class from another class whose constructor or destructor is private.
class Temp{
private:
Temp(){}
~Temp() { };
friend class FinalClass;
};
class FinalClass :
public Temp{. . .};
But, when you inherit any class from FinalClass, this works fine. Let's suppose you inherit the Drive class from FinalClass. Now, when you create the object of the Drive class, its constructor is called, which will call the constructor of FinalClass;
FinalClass's constructor calls the constructor of Temp because FinalClass is a friend of Temp.
So, everything is normal and our final class is still inheritable; in other words, it is not final until now.

Before going into the final class in more detail, let's discuss the famous multiple inheritance problem, the diamond problem. In that case, you solve that problem by making a virtual base class and inheriting intermediate classes virtually. But what is the purpose of the virtual base class? In fact, the object of most drive classes (whose object is created) directly calls the constructor of the virtual base class. So, we resolve the diamond problem because now the most drive class (Bottom, in the case of diamond problem) directly calls the most base class (Top, in the diamond problem) constructor, and now there is only a single copy of Top most class.


We can apply the same technique here. We inherit our FinalClass virtually from the Temp class and make Temp a virtual base class. Now, whenever anyone attempts to inherit a class from FinalClass and make an object of it, its constructor tries to call the constructor of Temp. But the constructor of Temp is private, so the compiler complains about this and it gives an error during the compilation because your derived class is not a friend of Temp.
Remember, friendship is not inherited in the drive class. After all, your parents' friends are not your friends and your friends are not friends of your children.

But, when you create an object of FinalClass, its constructor can call the Temp's constructor because FinalClass is a friend of Temp. So, here is the final version of the final class, which can also be created on the stack, not only on the heap.

class Temp{
private:
~Temp()
{ };
friend class FinalClass;
};
class FinalClass : virtual public Temp{. . .};


But, what is the case when you have to make more than one final class? You have to write double the classes; in other words, if you need N final classes, you have to write 2N classes in this method—one temp class with a private constructor and your final class. So, you have to write lots of the same code again and again. Why not try to take advantage of a template and try to make a class in such a way that if you inherit any class from that class, your class will automatically become the Final class. The code of such a class is so simple.

template
class MakeFinal
{
private:
MakeFinal(){};
~MakeFinal() { };
friend T;
};
Don't forget to virtually inherit your final class from this class to make sure this class becomes a virtual base class. And, pass your final class name as a template parameter so your class becomes a friend of this and can call the constructor of this class.

class FinalClass : virtual public MakeFinal{};

Of course, nothing comes without cost. You have to pay the extra bytes to store the information about the virtual base class. Most compiler implementations use a pointer to store the information about the virtual base class in case of virtual inheritance. Therefore, the size of the object is not just the sum of all the member variable storage allocation, but it is greater than you expect.

Remember, this pointer, the pointer to the virtual base class, is different than the virtual pointer, which introduces in the case of a virtual function [LIP96]. This is totally an implementation issue; C++ standard doesn't say anything about the mechanism of calling a virtual function, virtual pointer, and a virtual table [ISO98].
Adding only one small class and changing a few lines of code makes your program more reliable and reduces the resource leak problems, which could be created without introducing a final class.



What is virtual base class with example code.

#include
using namespace std;
class base
{public:
base()
{cout<<" calling base class constructor "<<<" calling derived class constructor"<<<" calling derived_1 class constructor "<<<" calling last class constructor "<
using namespace std;
class base
{public:
base()
{cout<<" calling base class constructor "<<<" calling derived class constructor"<<<" calling derived_1 class constructor "<<<" calling last class constructor "<


In C++, what is a constructor,destructor?

Constructor:This is a member of class which involkes when the object is created.Purpose of constructor is to intialise the objects with required values.

Destructor: It is a member of class which involkes when the object is out of scope.The purpose of destructor is to clear the heap memory.


What do you mean by inheritance?

Inheritance is the process of creating new classes, called derived classes, from existing classes or
base classes. The derived class inherits all the capabilities of the base class, but can add
embellishments and refinements of its own

what is the use of virtual destructor?

The order of execution of destructor in an inherited class during a clean up is like this.
1. Derived class destructor
2. Base class destructor
This is where the virtual mechanism comes into our rescue. By making the Base class Destructor virtual, both the destructors will be called in order. The following is the corrected sample.
#include
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<<"Destructor : Base"<<<"Constructor: Derived"<<<"Destructor : Derived"<What are advantages of pure virtual function?

To create a pure virtual function, rather than define a body for the function, we simply assign the function the value 0.
class Base
{
public:
const char* SayHi() { return "Hi"; } // a normal non-virtual function

virtual const char* GetName() { return "Base"; } // a normal virtual function

virtual int GetValue() = 0; // a pure virtual function
};

When we add a pure virtual function to our class, we are effectively saying, “it is up to the derived classes to implement this function


Pure Virtual Function
http://www.gotw.ca/gotw/031.htm


Why always array starts with index 0?

Array name is a constant pointer pointing to the base address(address of the first byte where the array begin) of the memory allocated. When you use arr[i], the compiler manipulates it as *(arr + i). Since arr is the address of the first element, the value of i must be 0 for accessing it. Hence all arrays begin with an index of 0.


What happens to the member pointers when an exception occurs in constructor, while allocating memory?How can we over come this ?




Differentiate Aggregation and containment?

Aggregation is a specialization of composition. When an outer object aggregates an interface of an inner object, it doesn't reimplement the interface - it merely passes the inner object's interface pointer directly to the client. So, it's less effort for the outer object. On the other hand, the outer object can't specialize the behaviour of the inner object.


The goal of aggregation is to convince the client that an interface implemented by the inner object is actually implemented by the outer object - the client should be unaware that there is more than one object in use.
However, the aggregation must be carefully managed so that the client can't use the IUnknown methods on the inner object.
For instance, since the client has a direct pointer to the inner object's IVehicle, the client could use this pointer to call QueryInterface and ask for ICar, at which point the inner object would return E_NOINTERFACE because it doesn't support ICar. This situation must be avoided in setting up aggregation.

Assuming you take care to accommodate the inherent schizophrenia in an aggregated object, aggregation is a more elegant solution than containment, although there is one limitation: if MTS is looking after your object, you can't use the object as part of an aggregate of non-MTS objects.

The following notes describe a very simple COM containment project, not using the ATL, just the raw COM API. The code in ..\Vehicle is for a simple COM object, which will be used as the inner contained object. The outer COM object is in ..\Car. A simple console client is in ..\Client. The ..\Registry directory contains some shared registry-update code. 




http://www.learncpp.com/cpp-tutorial/103-aggregation/

What is encapsulation?


Encapsulation is a single unit it contains the Data Member and Function Member. we can not directly.

Which command is used to delete all files in the current directory and all its sub-directories?
rm -rf *

what is shell?


A shell is a program that acts as an intermediary between the user and the operating system. It interprets what you type and passes it to the operating system.
When you login to a c shell, which script would be run first? (before the terminal is ready for the user)

When you login to a bash shell as a user, the /etc/profile and /etc/bashrc would be run.

How do you write a while loop in?

while [ condition ]
do
command1
command2
commandN
done

#!/bin/bash
c=1
while [ $c -le 5 ]
do
echo "Welcone $c times"
(( c++ ))
done


How do you find out what shell?


echo $SHELL

What is the conditional statement in shell scripting?

vi isnump_n
#!/bin/sh
#
# Script to see whether argument is positive or negative
#
if [ $# -eq 0 ]
then
echo "$0 : You must give/supply one integers"
exit 1
fi


How would you get the character positions 10-20 from a text file?


cat filename.txt cut -c 10-20

How do you list currently running process?

ps -ef will list all the Processes running in the System.

How do you fire a process in the background?


./process-name &


What is MUTEX?

1. Mutexes can synchronize threads within the same process orin other processes.
2. Mutexes can be used to synchronize threadsbetween processes if the mutexes

are allocated in writablememory and shared among the cooperating processes and have been initialized for this task.

http://www.geeksforgeeks.org/archives/9102
How do you count words, lines and characters in a file?

Wc

How do you do number comparison in shell scripts?
- -eq, -ne, -lt, -le, -gt, -ge


What is the difference between a 'thread' and a 'process'?



1.Threads share the address space of the process that created it; processes have their own address.
2.Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.

3.Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

4.Threads have almost no overhead; processes have considerable overhead.

5.New threads are easily created; new processes require duplication of the parent process.
6.Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.

7.Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

Write a shell script to identify the given string is palindrome or not?

$input_string = ;
chop($input_string);
$rev_string = reverse($input_string);
if($input_string eq $rev_string){print("The string is a palindrome");}
else{print("The string is NOT a palindrome");}




What is INODE?

The inode is the focus of all file activity in the file system. There is a unique inode allocated for each active file, each current directory, each mounted-on file, text file, and the root. An inode is "named" by its device/i-number pair.


What does $# stand for?

$# means, number of positional parameters set

Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?

There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor is a code which is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.

Can a copy constructor accept an object of the same class as parameter, instead of reference
of the object?


No. It is specified in the definition of the copy constructor itself. It should generate an error if
a programmer specifies a copy constructor with a first argument that is an object and not a
reference

What is conversion operator?


class can have a public method for specific data type conversions.
for example:
class Boo
{
double value;
public:
Boo(int i )
operator double()
{
return value;
}
};
Boo BooObject;
double i = BooObject;
// assigning object to variable i of type double.
now conversion operator gets called to assign the value.

What is "placement new" and why would I use it?.

There are many uses of placement new. The simplest use is to place an object at a particular location in memory. This is done by supplying the place as a pointer parameter to the new part of
a new expression.




#include // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred
void someCode()
{
char memory[sizeof(Fred)]; // Line #1
void* place = memory; // Line #2
Fred* f = new(place) Fred(); // Line #3 (see "DANGER" below)
// The pointers f and place will be equal
...
}

Line #1 creates an array of sizeof(Fred) bytes of memory, which is big enough to hold a Fred
object.

Line #2 creates a pointer place that points to the first byte of this memory (experienced C
programmers will note that this step was unnecessary; it's there only to make the code more
obvious).

Line #3 essentially just calls the constructor Fred::Fred(). The this pointer in the Fred
constructor will be equal to place. The returned pointer f will therefore be equal to place.

ADVICE: Don't use this "placement new" syntax unless you have to. Use it only when you really
care that an object is placed at a particular location in memory. For example, when your hardware has a memory-mapped I/O timer device, and you want to place a Clock object at that memory location

Difference between realloc() and free()?

The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur.

The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer

What will happen if I say delete this


if you say "delete this", you are effectively calling the destructor twice, which could well be a disaster if your class uses heap. The destructor will be called when you say " delete this " and again when that object goes out of scope. Since this is the language behavior, there is no way to prevent the destructor from being called twice.




Anybody knows how to convert object of one class to object of another class using type conversion? i read in a c++ book simply assign it like this obj1=obj2 where both are objects of different classes..but its not working..plz tell ..thanks in advance :)

You cannot try a conversion objects of two different classes by simple assignment. You can do either of overloading the assignment operator or writing a conversion routine in your source object. The code for the latter can be as follows:

class A
{
private:
int aa;
public: A(){aa=0;}
};
class B
{ private:
int bb;
public: B(int y)
{bb=y;}
operator A()
{ int aa = bb/2;}
};

void main(){
A a1,a2;
B b1(20);B b2(30);
a1=b1;a2=b2;

}


after the assigment statements in main() a1.aa will be 10 and a2.aa will be 15. Hope this helps..Alternatively if you do not have access to source class code you can write a similar routine in destination class as well

Singleton Pattern & its implementation with C++


Suppose we have to use a single object of a class throughout the lifetime of an application. In C++, it is possible to declare a global object, which can be used anywhere inside the program. But a good object oriented design strictly prohibits the use of global variables or methods, since they are against the fundamental principles of object orientation like data encapsulation or data hiding. More over, most latest object oriented programming languages like JAVA or C# do not support global variables or functions.

Another practical solution to get a single object is by declaring a class, which contains only static methods. A static class is loaded into memory when the execution of the program starts and it remains there till the application ends. Remember that for invoking a static method of a class, it is not necessary to create an instance of the class. But remember that a class with only static methods and variables are not a good object oriented design. A class of static methods unfortunately breaks down to a list of functions or utilities.

When we want to create only one instance of a class in a truly object oriented fashion by adhering to the basic principles of object oriented programming, the Singleton patterns are used. The Singleton Pattern comes under that classification of Creational Pattern, which deals with the best ways to create objects. The Singleton Design pattern is used, where only one instance of an object is needed throughout the lifetime of an application. The Singleton class is instantiated at the time of first access and same instance is used thereafter till the application quits.
There are very good non-software examples available in real world for Singleton patterns. The office of the Principal of my college is a Singleton. The University specifies the means by which a principal is selected, limits the term of office, and defines the order of succession. As a result, there can be at most one active principal at any given time. Regardless of the personal identity of the principal, the title, "The Principal" is a global point of access that identifies the person in the office.

The Singletons are often used to control access to resources such as database connections or sockets. Suppose we have a license for only one connection for our database. A Singleton connection object makes sure that only one connection can be made at any time.

It is pretty easy to implement the Singleton Pattern in any object oriented programming languages like C++, JAVA or C#. There are lots of different ways to implement the Singleton Pattern. But by using a private constructor and a static method to create and return an instance of the class is a popular way for implementing Singleton Pattern. The UML representation of a Singleton Pattern is shown below.

/*
Creational Pattern: SINGLETON
Author: Rajesh V.S
Language: C++
Email: rajeshvs@msn.com
*/

#include


using namespace std;

class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor

}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}



void Singleton::method()
{
cout << "Method of the singleton class" << endl; } 

int main() { Singleton *sc1,*sc2; sc1 = Singleton::getInstance(); sc1->method();
sc2 = Singleton::getInstance();
sc2->method();

return 0;
}

More info about Design Pattern


http://sourcemaking.com/design_patterns/factory_method

Find the size of an interger data type with out using sizeof() function?
A: #include
int main()
{
int *i ;
int *j = i + 1;
cout << " size of an integer variable i = " << (int)j - (int)i <What is faster ++i or i++, where i is an interger variable?

The answer to this lies in the fact, how they used. With ++i(PreIncrement) the variable is incremented and new value is returned. So it requires one instruction to increment the variable.
In case of i++(post Increment), the old value has to be returned or used in the expression and then the variable is incrememented after the expression is evaluated. Since you need one instruction to save the old value to be used in the expression and other instruction to increment
the variable, its comparatively slower.

What are C++ storage classes


auto: the default. Variables are automatically created and initialized when they are defined and
are destroyed at the end of the block containing their definition. They are not visible
outside that block.
register: a type of auto variable. a suggestion to the compiler to use a CPU register for
performance.
static: a variable that is known only in the function that contains its definition but is never
destroyed and retains its value between calls to that function. It exists from the time the
program begins execution.
extern: a static variable whose definition and placement is determined when all object and library
modules are combined (linked) to form the executable code file. It can be visible outside
the file where it is defined.

How can I provide printing for an entire hierarchy of classes?

class Base {
public:
friend std::ostream& operator<< (std::ostream& o, const Base& b); ... protected: virtual void printOn(std::ostream& o) const; }; inline std::ostream& operator<< (std::ostream& o, const Base& b) { b.printOn(o); return o; } class Derived : public Base { protected: virtual void printOn(std::ostream& o) const; };


Please feel free to provide comment and add question for making better documentation



Can main have return value of int

the return value for main should indicate how the program exited. Normal exit is generally represented by a 0 return value from main.

Abnormal termination is usually signalled by a non-zero return but there is no standard for how non-zero codes are interpreted.
Also as noted by others, void main() is explicitly prohibited by the C++ standard and shouldn't be used. The valid C++ main signatures are:

int main()
and
int main(int argc, char* argv[])


although many will also acceptint main(int argc, char** argv)

It's also worth noting that in C++, int main() can be left without a return value at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0 should be omitted or not is open to debate. The range of valid C program main signatures is much greater.

Also, efficiency is not an issue with the main function. It can only be entered and left once (marking program start and termination) according to the C++ standard. For C, the case is different and re-entering main() is allowed, but should probably be avoided.

What is Difference between c and c++?

both C and C++ are programming languages. C++ is termed as superset of C.
C is a powerful and elegent language.almost all c PROGRAMS ARE ALSO c++ PROGRAMS.in C, it facilitates--" topdown structured design" as against C++ provides bottom-up object-oriented design.

the C language is built from functions (like printf)that execute different tasks. in c++, it is a object-oriented system. objects are considered to be "a partitioned area of computer memory" that stores data and set of operations that can access that data.the three most important facilities that c++ adds on to are classes, function overloading and operator overloading.


What is the difference between composition and inheritance?

Composition and inheritance is totally different from each other.

composition means compose the properties by code of same class in composition we can refer some other class who hold same properties but we have to code we can not directly use that code ,we have to rewrite .
But inheritance i.e inherit the properties of other class .in it method of class to whom we inherit can directly call by the child class object.

if we think as real life example if we inspired by someone we adope the properties of that person we have to add that quality of person ourself ,that is composition. but some quality of our parent automatically in us there is no need to strive ,that is inheritance.

Is there any way to write a class such that no class can be inherited from it. Please include code

It is a common question, "Why shouldn't we inherit a class from STL classes?" The answer to this question is simple—the Big Three rule [CLI95].

In other words, you should have a virtual destructor in a class if you want to make it a base class. However, there isn't any class in STL that defines a virtual destructor. Even if you try to inherit a class from STL class, the compiler doesn't complain about it, although there is a high chance of a resource leak in the program. It makes a programmer's life easy if the compiler catches as many errors as it can during compilation. So, it is a nice idea to make a class in such a way that just anyone can't inherit class from it; in other words, you can create a Final class.

One day, during a discussion with one of my friends, who mostly works on Java, we compared the object-oriented features of Java and C++. He introduced me one interesting concept of Java, called the Final class; it's a class from which you can't inherit any further classes. It was a totally new concept for me at that time and I like it because most of the time I wish I could make a class in C++ from which others can't inherit. He asked me to do this in C++ and I started thinking on it and doing some experimentation. Before further discussion about how can we make it, it is useful to discuss why should we need it.

The Need for a Final Class

One possible scenario that comes in mind that would be useful for a "Final class" is a class without a virtual destructor. Suppose you are making a class that doesn't have a virtual destructor; it may contain some dynamically allocated object. Now, if anyone inherits a class from it and creates the object of the derived class dynamically, it will clearly create a memory leak although the compiler will not complain about this.

class B {. . .};
class D : public B {. . .};
B* pB = new D;delete pB;
// resource leak