Tuesday, June 22, 2010

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
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()


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 {
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
{ }
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{
~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{
{ };
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.

class 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.

using namespace std;
class base
{cout<<" calling base class constructor "<<<" calling derived class constructor"<<<" calling derived_1 class constructor "<<<" calling last class constructor "<
using namespace std;
class 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.
class Base
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
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

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. 


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 ]

while [ $c -le 5 ]
echo "Welcone $c times"
(( c++ ))

How do you find out what shell?

echo $SHELL

What is the conditional statement in shell scripting?

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

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.

How do you count words, lines and characters in a file?


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 = ;
$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

What is conversion operator?

class can have a public method for specific data type conversions.
for example:
class Boo
double value;
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

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

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
int aa;
public: A(){aa=0;}
class B
{ private:
int bb;
public: B(int y)
operator A()
{ int aa = bb/2;}

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


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


using namespace std;

class Singleton
static bool instanceFlag;
static Singleton *single;
//private constructor

static Singleton* getInstance();
void method();
instanceFlag = false;

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
if(! instanceFlag)
single = new Singleton();
instanceFlag = true;
return single;
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();

return 0;

More info about Design Pattern


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
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 {
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()
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