/*----------------------------------------------------- Script for AdSense -----------------------------------------------------*/ /* */ /* Footer ----------------------------------------------- */ #footer { clear: both; text-align: center; color: #333333; } #footer .widget { margin:.5em; padding-top: 20px; font-size: 85%; line-height: 1.5em; text-align: left; } /** Page structure tweaks for layout editor wireframe */ body#layout #header { width: 750px; } -->

Thursday, April 29, 2010

Operator Overloading

When an operator is overloaded, none of its original meaning is lost. It simply means that a new operation relative to a specific class is defined.
To overload an operator, you must define what that operation means relative to the class that it is applied to. To do this you create an operator function, which defines its action. The general form of a member operator function is


type classname::operator#(arg-list)
{

// operation defined relative to the class
}


This program overloads the + operators relative to the Complex class: from MSDN



// operator_overloading.cpp
// compile with: /EHsc
#include <iostream>

using namespace
std;
class
Complex
{

public
:
Complex( double r, double i ) : re(r), im(i) {}
Complex operator+( Complex &other );
void
Display( ) { cout << re << ", " << im << endl; }
private
:
double
re, im;
};


// Operator overloaded using a member function
Complex Complex::operator+( Complex &other )
{

return
Complex( re + other.re, im + other.im );
}


int
main()
{

Complex a = Complex( 1.2, 3.4 );
Complex b = Complex( 5.6, 7.8 );
Complex c = Complex( 0.0, 0.0 );

c = a + b;
c.Display();
}




friend Operator Functions:
It is possible for an operator function to be a friend of a class rather than a member. since friend functions are not members of a class, they do not have the implied argument this. Therefore, when a friend is used to overload an operator, both operands are passed when overloading binary operators and a single operand is passed when overloading unary operators.
The only operators that cannot use friend functions are =, ( ), [ ], and ->. The rest can use either member or friend functions to implement the specified operation relative to its class.
As friend overloaded function require two operand then we can do object + int addition or int + object using friend +operator overloading.


Read more...

Wednesday, April 28, 2010

C++ Interview Questions: 2

What is Friend function? Can derived class inherit friend function too?

It is possible for a nonmember function to have access to the private members of a class by declaring it as a friend of the class.
For example, here frd( ) is declared to be a friend of the class cl:

class cl {
.
.
.

public
:
friend
void frd();
.
.
.
};


One reason that friend functions are allowed in C++ is to accommodate situations in which, for the sake of efficiency.
In below example The same_color( ) function is defined as



// Return true if line and box have same color.
int same_color(line l, box b)
{

if
(l.color==b.color) return 1;
return
0;
}


As you can see, the same_color( ) function needs access to the private parts of both line and box to perform its task efficiently. Being a friend of each class grants it this access privilege. Further, notice that because same_color( ) is not a member, no scope resolution operator or class name is used in its definition.


#include <iostream.h>
#include <conio.h>

class
line;

class
box {
int
color; // color of box
int upx, upy; // upper left corner
int lowx, lowy; // lower right corner
public:
friend
int same_color(line l, box b);
void
set_color(int c);
void
define_box(int x1, int y1, int x2, int y2);
void
show_box();
} ;


class
line {
int
color;
int
startx, starty;
int
len;
public
:
friend
int same_color(line l, box b);
void
set_color(int c);
void
define_line(int x, int y, int l);
void
show_line();
} ;


// Return true if line and box have same color.
int same_color(line l, box b)
{

if
(l.color==b.color) return 1;
return
0;
}


void
box::set_color(int c)
{

color = c;
}


void
line::set_color(int c)
{

color = c;
}


void
box::define_box(int x1, int y1, int x2, int y2)
{

upx = x1;
upy = y1;
lowx = x2;
lowy = y2;
}


void
box::show_box()
{

int
i;

textcolor(color);

gotoxy(upx, upy);
for
(i=upx; i<=lowx; i++) cprintf("-");

gotoxy(upx, lowy-1);
for
(i=upx; i<=lowx; i++) cprintf("-");

gotoxy(upx, upy);
for
(i=upy; i<=lowy; i++) {
cprintf("");
gotoxy(upx, i);
}


gotoxy(lowx, upy);
for
(i=upy; i<=lowy; i++) {
cprintf("");
gotoxy(lowx, i);
}
}


void
line::define_line(int x, int y, int l)
{

startx = x;
starty = y;
len = l;
}


void
line::show_line()
{

int
i;

textcolor(color);

gotoxy(startx, starty);

for
(i=0; i<len; i++) cprintf("-");
}


int
main()
{

box b;
line l;

b.define_box(10, 10, 15, 15);
b.set_color(3);
b.show_box();

l.define_line(2, 2, 10);
l.set_color(2);
l.show_line();

if
(!same_color(l, b)) cout << "Not the same.\n";
cout << "\nPress a key.";
getch();

// now, make line and box the same color
l.define_line(2, 2, 10);
l.set_color(3);
l.show_line();

if
(same_color(l, b)) cout << "Are the same color.\n";

return
0;
}


Note: There are two important restrictions that apply to friend functions.
1) A derived class does not inherit friend functions.
2) friend functions may not have a storage-class specifier.
That is, they may not be declared as static or extern.

What is Inline function? How do you decide to make function inline?


one very important C++ feature not found in C is the inline function. An inline function is a function whose code is expanded inline at the point at which it is called instead of actually being called.
This is much like a parameterized function-like macro in C, but more flexible.
consider the following example code for Inline function.

#include <iostream.h>

class
myclass {
int
i;
public
:
int
get_i();
void
put_i(int j);
} ;


inline
int myclass::get_i()
{

return
i;
}


inline
void myclass::put_i(int j)
{

i = j;
}


int
main()
{

myclass s;

s.put_i(10);
cout << s.get_i();

return
0;
}


If you compile this version of the program and compare it to a compiled version of the program in which inline is removed, the inline version is several bytes smaller. Also, calls to get_i( ) and put_i( ) will execute faster.
Note: It is important to understand that, technically, inline is a request, not a command, to the compiler to generate inline code. There are various situations that can prevent the compiler from complying with the request. For example, some compilers will not inline a function if it contains a loop, a switch, or a goto.

The second way to create an inline function is to define the code to a function inside a class declaration.


#include <iostream.h>

class
cl {
int
i;
public
:
// automatic inline functions
int get_i() { return i; }
void
put_i(int j) { i = j; }
} ;


Read more...

C++ Interview questions:1

Can you explain the mechanism that if I pass the object to a function then it is a call by value or call by ref?

Passing an Object to a function is call by value type.

Then will it call consturctor everytime when you pass an object as a parameter?

Objects may be passed to functions in just the same way that any other type of variable can. Objects are passed to functions through the use of the standard call-by- value mechanism. This means that a copy of an object is made when it is passed to a function. But when a copy of an object is generated because it is passed to a function, the object's constructor function is not called. However, when the copy of the object inside the function is destroyed, its destructor function is called.


Take an example code for passing an object to a function.


#include <iostream.h>

class
myclass {
int
i;
public
:
myclass(int n);
~
myclass();
void
set_i(int n) {i=n;}
int
get_i() {return i;}
};


myclass::myclass(int n)
{

i = n;
cout << "Constructing " << i << "\n";
}


myclass::~myclass()
{

cout << "Destroying " << i << "\n";
}


void
f(myclass ob);

int
main()
{

myclass o(1);

f(o);
cout << "This is i in main: ";
cout << o.get_i() << "\n";

return
0;
}


void
f(myclass ob)
{

ob.set_i(2);

cout << "This is local i: " << ob.get_i();
cout << "\n";
}


This program produces this output:


Constructing 1
This is local i: 2
Destroying 2
This is i in main: 1
Destroying 1

Note 1: By default, when a copy of an object is made, a bitwise copy occurs. This means that the new object is an exact duplicate of the original.
The fact that an exact copy is made can, at times, be a source of trouble.
it is possible to prevent this type of problem by defining the copy operation relative to your own classes by creating a special type of constructor called a copy constructor.

Note 2:When an object is returned by a function, a temporary object is automatically created, which holds the return value. It is this object that is actually returned by the function. After the value has been returned, this object is destroyed. The destruction of this temporary object may cause unexpected side effects in some situations. For example, if the object returned by the function has a destructor that frees dynamically allocated memory, that memory will be freed even though the object that is receiving the return value is still using it.

to overcome this problem that involve overloading the assignment operator and defining a copy constructor.

Can I copy one object to another? How?
Yes.
1) using assignment operator
2) it is possible to overload the assignment operator and define some other assignment procedure.

Note: By default, all data from one object is assigned to the other by use of a bit-by-bit copy.


myclass ob1, ob2;
ob2 = ob1; // assign data from ob1 to ob2


When to use "." and when to use "->" while using pointers in C++?



To access a member of an object when using the actual object itself, you use the dot ( . ) operator.
To access a specific member of an object when using a pointer to the object, you must use the arrow operator (->).


#include <iostream.h>

class
myclass {
int
i;
public
:
void
set_i(int n) {i = n;}
void
show_i();
};


void
myclass::show_i()
{

cout << i << "\n";
}


int
main()
{

myclass ob, *p; // declare an object and pointer to it

ob.set_i(1); // access ob directly

ob.show_i();

p = &ob; // assign p the address of ob
p->show_i(); // access ob using pointer

return
0;
}


Read more...

Classes, Structure and Union are related

Classes and Structures Are Related

Classes and Structure are very similer.The only difference is that by default the members of a class are private while, by default, the members of a struct are public. According to the formal C++ syntax, a struct defines a class type.
In fact, with one exception, they are interchangeable because the C++ struct can include data and the code that manipulates that data in the same way that a class can.

For the most part, C++ programmers use class when defining an object that contains both code and data. They use struct when defining a data-only object. (That is, struct is usually used in a way that is compatible with C-style structures.)

Unions and Classes Are Related


A union is essentially a structure in which all elements are stored in the same location. A union can contain constructor and destructor functions as well as member and friend functions. Like a structure, union members are public by default.
It is important to understand that, like a structure, a union declaration in C++ defines a class-type.
There are several restrictions that must be observed when you use C++ unions.
1) A union cannot inherit any other classes of any type.
2) A union cannot be a base class.
3) A union cannot have virtual member functions.
4) No static variables can be members of a union.
5) A union cannot have as a member any object that overloads the = operator.

Anonymous Union:
An anonymous union is a union that has neither a tag name nor any objects specified in its declaration. Also, global anonymous unions must be specified as static. Anonymous unions may not contain member functions. Finally, anonymous unions cannot include private or protected members.

Note: just because C++ gives unions greater power and flexibility does not mean that you have to use it. In cases where you simply need a C-style union, you are free to use one in that manner. However, in cases where you can encapsulate a union along with the routines that manipulate it, you add considerable structure to your program.




Read more...

Friday, April 23, 2010

Virtual Address Space.

Every process is given its very own virtual address space. For 32-bit processes, this address space is 4 GB, since a 32-bit pointer can have any value from from 0 to (2^32)-1

For 64-bit processes, this address space is 16 EB (exabytes), since a 64-bit pointer can have any value from 0 to (2^64) - 1
Since every process receives its very own private address space, when a thread in a process is running, that thread can access memory that belongs only to its process.

Virtual Address Space Mapping (partitioned) in 32-bit processor.

VAS 1 |---vvvv-------vvvvvv---vvvv----vv---v----vvv--|
mapping |||| |||||| |||| || | |||
file bytes app1 app2 kernel user system_page_file
mapping |||| |||||| |||| || |
VAS 2 |--------vvvv--vvvvvv---vvvv-------vv---v------|

Source: Wikipedia and my summary notes from my diary.

Read more...

Thread Synchronization With Kernel Objects : 3

After Events, Now we will discuss Semaphore and Mutex Kernel Objects.

Semaphore Kernel Objects
Semaphore kernel objects are used for resource counting.

Let's say that I'm developing a server process in which I have allocated a buffer that can hold client requests. I've hard-coded the size of the buffer so that it can hold a maximum of five client requests at a time. If a new client attempts to contact the server while five requests are outstanding, the new client is turned away with an error indicating that the server is busy and the client should try again later. When my server process initializes, it creates a thread pool consisting of five threads, each thread ready to process individual client requests as they come in.


Initially, no clients have made any requests, so my server doesn't allow any of the threads in the pool to be schedulable. However, if three client requests come in simultaneously, three threads in the pool should be schedulable. You can handle this monitoring of resources and scheduling of threads very nicely using a semaphore: the maximum resource count is set to 5 since that is the size of my hard-coded buffer. The current resource count is initially set to 0 since no clients have made any requests. As client requests are accepted, the current resource count is incremented

The rules for a semaphore are as follows:


1) If the current resource count is greater than 0, the semaphore is signaled.


2) If the current resource count is 0, the semaphore is nonsignaled.


3) The system never allows the current resource count to be negative.


4) The current resource count can never be greater than the maximum resource count.

Win32 APIs for semaphore object.

CreateSemaphore()//.....//API to create semaphore object.
OpenSemaphore()//.....// open semaphore object.
ReleaseSemaphore()//......//Release semaphore object.

Mutex kernel Object
Mutex kernel objects ensure that a thread has mutual exclusive access to a single resource.
A mutex object contains a usage count, a thread ID, and a recursion counter. Mutexes behave identically to critical sections, but mutexes are kernel objects, while critical sections are user-mode objects. This means that mutexes are slower than critical sections.
thread can specify a timeout value while waiting to gain access to a resource.

The thread ID identifies which thread in the system currently owns the mutex,
and the recursion counter indicates the number of times that this thread owns the mutex.Typically, they are used to guard a block of memory that is accessed by multiple threads.

The rules for a mutex are as follows:


1) If the thread ID is 0 (an invalid thread ID), the mutex is not owned by any thread and is signaled.


2) If the thread ID is nonzero, a thread owns the mutex and the mutex is nonsignaled.

Win32 APIs for Mutex Kernel Object.
CreateMutex()//.......API to create mutex object.

OpenMutex()//......API to open mutex object.

ReleaseMutex()//....API to release mutex object.



Read more...

Thread Synchronization With Kernel Objects : 2

Event Kernel Object.

There are two different types of event objects: manual-reset events and auto-reset events.
When a manual-reset event is signaled, all threads waiting on the event become schedulable.
When an auto-reset event is signaled, only one of the threads waiting on the event becomes schedulable.
Events are most commonly used when one thread performs initialization work and then signals another thread to perform the remaining work.
The event is initialized as nonsignaled, and then after the thread completes its initial work, it sets the event to signaled.


At this point, another thread, which has been waiting on the event, sees that the event is signaled and becomes schedulable.
This second thread knows that the first thread has completed its work.
For example, you in your mobile application, you are getting an incoming call.
You have created an event for that.

There are set of WIN32 APIs for event kernel object.
CreateEvent(...); // API to Create Event
OpenHandle(...); // API to get Event Handles
SetEvent(...); // API to put an event in signaled state.
ResetEvent(...); // API to put an event in non signaled state.
CloseHandle(...); // API to close Event Handles

One Practicle example: In our mobile application, when we are on call, (incoming, outgoing, 2nd call (one call is already on hold etc). You need to write such functionality into thread. so, that while one call is in process, user can not accept another call before finishing that call or put it on hold. but all these things to be properly designed else you may loose control on your functionality.

First of all, you need to create specific threads and events.

// Create an Auto Reset Event which automatically reset to Non Signalled state after being signalled
IncomingCallEvent
// Create a Thread Which will wait for the events to occur
ON_CALL (here switch case....incoming call, outgoing call, 2nd call (one call is already on hold) etc....you must have specified)
// Signal the event
SetEvent ( hEvent ); (pass appropriate event based on switch-case ...here guass you are passing IncomingCallEvent)
// Wait for the Thread to Die
WaitForSingleObject ( hThrd, INFINITE ); and then close both handle (event and thread)

// Standard include headers
#include <windows.h>
#include <iostream> u
sing namespace std;
DWORD WINAPI ON_CALL ( LPVOID n )
{

cout<<"Thread Instantiated........."<<endl;
// Get the handler to the event for which we need to wait in // this thread.
HANDLE hEvent = OpenEvent ( EVENT_ALL_ACCESS , false, "IncomingCallEvent" );
if
( !hEvent ) { return -1; }
// wait for an event to occur

// Wait for the Event
WaitForSingleObject ( hEvent, INFINITE );
// No need to Reset the event as its become non signaled as soon as
// some thread catches the event.

cout<<"Got The signal......."<<endl;

CloseHandle(hEvent);
cout<<"End of the CALL......"<<endl;
return
0;
}


int
main()
{

// Create an Auto Reset Event which automatically reset to
// Non Signalled state after being signalled
HANDLE hEvent = CreateEvent ( NULL , false , false , "IncomingCallEvent" );
if
( !hEvent ) return -1;
// Create a Thread Which will wait for the events to occur
DWORD Id;
HANDLE hThrd = CreateThread ( NULL, 0, (LPTHREAD_START_ROUTINE)ON_CALL ,0,0,&Id );
if( !
hThrd )
{
CloseHandle (hEvent); return -1;
}

// Signal the event
SetEvent ( hEvent );
Wait for the Thread to Die
WaitForSingleObject ( hThrd, INFINITE );
CloseHandle ( hThrd );
CloseHandle ( hEvent );
cout<<"End of Main ........"<<endl;
return
0;
}



One more example I can explain. When we are writing word document, that time we have grammer check, spelling check, word count check functionality.
such functionality if we want to write then we can create seperate threads for respected functionalities and set appropriate event.
It can be either manual reset or auto rest as per the requirement.

Ideally, they all threads will get CPU time and access the memory block. Notice that all three threads will access the memory in a read-only fashion. This is the only reason why all three threads can run simultaneously.

Read more...

Thread Synchronization With Kernel Objects:1

In previous post we saw how to synchronize threads using mechanisms that allow your threads to remain in user mode. The wonderful thing about user-mode synchronization is that it is very fast.
While user-mode thread synchronization mechanisms offer great performance, they do have limitations, and for many applications they simply do not work.
1) For example, the interlocked family of functions operates only on single values and never places a thread into a wait state.
2) You can use critical sections to place a thread in a wait state, but you can use them only to synchronize threads contained within a single process.
3) You can easily get into deadlock situations with critical sections because you cannot specify a timeout value while waiting to enter the critical section.


Now lets see how we can synchornize threads using kernel objects.kernel objects are far more versatile than the user-mode mechanisms.the only bad side to kernel objects is their performance.
calling thread must transition from user mode to kernel mode. This transition is costly: it takes about 1000 CPU cycles
For thread synchronization, each of these kernel objects is said to be in a signaled or nonsignaled state. The toggling of this state is determined by rules that Microsoft has created for each object.
For example, process kernel objects are always created in the nonsignaled state. When the process terminates, the operating system automatically makes the process kernel object signaled. Once a process kernel object is signaled, it remains that way forever; its state never changes back to nonsignaled.
A process kernel object is nonsignaled while the process is running, and it becomes signaled when the process terminates.
If you want to write code that checks whether a process is still running, all you do is call a function that asks the operating system to check the process object's Boolean value.
Threads can put themselves into a wait state until an object becomes signaled.
The following kernel objects can be in a signaled or nonsignaled state:
1) Processes
2) Threads
3) Jobs
4) Files
5) Console Input
6) File change notifications
7) Events
8) Waitable timers
9) Semaphores
10) Mutexes

Wait Functions
In my previous experience application development, I was using these wait functions. there wer 6 threads for galileo receiver to run simulteneously and feed the data to the receiver input.
There are two wait functions.
1) Here's an example of how to call WaitForSingleObject with a timeout value other than INFINITE:

DWORD dw = WaitForSingleObject(hProcess, 5000);
switch
(dw) {

case
WAIT_OBJECT_0:
// The process terminated.
break;

case
WAIT_TIMEOUT:
// The process did not terminate within 5000 milliseconds.
break;

case
WAIT_FAILED:
// Bad call to function (invalid handle?)
break;
}


2) example using WaitForMultipleObjects function.

HANDLE h[3];
h[0] = hProcess1;
h[1] = hProcess2;
h[2] = hProcess3;
DWORD dw = WaitForMultipleObjects(3, h, FALSE, 5000);
switch
(dw) {
case
WAIT_FAILED:
// Bad call to function (invalid handle?)
break;

case
WAIT_TIMEOUT:
// None of the objects became signaled within 5000 milliseconds.
break;

case
WAIT_OBJECT_0 + 0:
// The process identified by h[0] (hProcess1) terminated.
break;

case
WAIT_OBJECT_0 + 1:
// The process identified by h[1] (hProcess2) terminated.
break;

case
WAIT_OBJECT_0 + 2:
// The process identified by h[2] (hProcess3) terminated.
break;
}


Source: Summary note from my diary (I learnt these concepts long back)

Read more...

Thread Synchronization in User Mode:2

Critical Sections:
A critical section is a small section of code that requires exclusive access to some shared resource before the code can execute. This is a way to have several lines of code "atomically" manipulate a resource. By atomic, I mean that the code knows that no other thread will access the resource.system will not schedule any other threads that want to access the same resource until your thread leaves the critical section.


CRITICAL_SECTION g_cs;
DWORD WINAPI ThreadFun1(PVOID pvParam)
{

while
()
{

EnterCriticalSection(&g_cs);
//......write code. do manipulation (use global resource)
LeaveCriticalSection(&g_cs);
}

return
(0);
}

DWORD WINAPI ThreadFun2(PVOID pvParam)
{

while
()
{

EnterCriticalSection(&g_cs);
//......write code. do manipulation (use global resource)
LeaveCriticalSection(&g_cs);
}

return
(0);
}


allocate a CRITICAL_SECTION data structure, g_cs, and then wrapp any code that touches the shared resource.
Notice that I passed the address of g_cs in all calls to EnterCriticalSection and LeaveCriticalSection.
CRITICAL_SECTION is defined in WinNT.h.
Normally CRITICAL_SECTION structures are allocated as global variables.
CRITICAL_SECTION structures can be allocated as local variables or dynamically allocated from a heap.
There are just two requirements. The first is that all threads that want to access the resource must know the address of the CRITICAL_SECTION structure that protects the resource. You can get this address to these threads using any mechanism you like. The second requirement is that the members within the CRITICAL_SECTION structure be initialized before any threads attempt to access the protected resource.
CRITICAL_SECTION structure is initialized by calling VOID InitializeCriticalSection(PCRITICAL_SECTION pcs);
CRITICAL_SECTION structure can be clean up by calling VOID DeleteCriticalSection(PCRITICAL_SECTION pcs);

Don't Hold Critical Sections for a Long Time
When a critical section is held for a long time, other threads might enter wait states, which will hurt your application's performance.
It's impossible to tell how much time the window procedure requires for processing the WM_SOMEMSG message—it might be a few milliseconds or a few years. During that time, no other threads can gain access to the g_s structure. It's better to write the code as follows:
SOMESTRUCT g_s;
CRITICAL_SECTION g_cs;

DWORD WINAPI SomeThread(PVOID pvParam) {

EnterCriticalSection(&g_cs);
SOMESTRUCT sTemp = g_s;
LeaveCriticalSection(&g_cs);

// Send a message to a window.
SendMessage(hwndSomeWnd, WM_SOMEMSG, &sTemp, 0);
return
(0);
}


This code saves the value in sTemp, a temporary variable. You can probably guess how long the CPU requires to execute this line—only a few CPU cycles. Immediately after the temporary variable is saved, LeaveCriticalSection is called because the global structure no longer needs to be protected.
other threads are stopped from using the g_s structure for only a few CPU cycles instead of for an unknown amount of time.

Source: Summary note from my diary.(when I learnt these concepts long back.

Read more...

Thread Synchronization in User Mode:1

All threads in the system must have access to system resources such as heaps, serial ports, files, windows, and countless others. If one thread requests exclusive access to a resource, other threads cannot get their work done.
Threads need to communicate with each other in two basic situations:
When you have multiple threads accessing a shared resource in such a way that the resource does not become corrupt
When one thread needs to notify one or more other threads that a specific task has been completed.

Windows offers many facilities to make thread synchronization easy.

atomic access: A big part of thread synchronization has to do with atomic access—a thread's ability to access a resource with the guarantee that no other thread will access that same resource at the same time. Let's look at a simple example:

// Define a global variable.
long g_x = 0;

DWORD WINAPI ThreadFunc1(PVOID pvParam) {
g_x++;
return
(0);
}


DWORD WINAPI ThreadFunc2(PVOID pvParam) {
g_x++;
return
(0);
}


MOV EAX, [g_x] ; Thread 1: Move 0 into a register.
INC EAX ; Thread 1: Increment the register to 1.

MOV EAX, [g_x] ; Thread 2: Move 0 into a register.
INC EAX ; Thread 2: Increment the register to 1.
MOV [g_x], EAX ; Thread 2: Store 1 back in g_x.

MOV [g_x], EAX ; Thread 1: Store 1 back in g_x.


If the code executes this way, the final value in g_x is 1—not 2 as you expect! This is pretty scary.
To solve the problem above, we need something simple. We need a way to guarantee that the incrementing of the value is done atomically—that is, without interruption. The interlocked family of functions provides the solution we need.

// The long variable shared by many threads
LONG g_x;



// Incorrect way to increment the long
g_x++;



// Correct way to increment the long
InterlockedExchangeAdd(&g_x, 1);


interlocked functions assert a hardware signal on the bus that prevents another CPU from accessing the same memory address.

Read more...

Wednesday, April 21, 2010

Abstract and Sealed Class

The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.

The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.


public abstract class A
{

// Class members here.
}



An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:


public abstract class A
{

public
abstract void DoWork(int i);
}




A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class,
A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class.


public class D : C
{

public
sealed override void DoWork() { }
}






Read more...

Interface and abstract class

Sometimes it is simple and helpful to define a class that does nothing but defines a standardised interface that can be used by other classes to make sure the implementation follows a standard set of input and output paramaters. Also this approach results in faster code runs and more maintainable code.

An interface is a reference type that is somewhat similar to an abstract base class that consists of only abstract members. When a class derives from an interface, it must provide an implementation for all the members of the interface. A class can implement multiple interfaces even though it can derive from only a single direct base class.

An interface has the following properties:
An interface is like an abstract base class: any non-abstract type inheriting the interface must implement all its members.
An interface cannot be instantiated directly.
Interfaces can contain events, indexers, methods and properties.
Interfaces contain no implementation of methods.
Classes and structs can inherit from more than one interface.
An interface can itself inherit from multiple interfaces.



#include<iostream>

using namespace
std;

//Shape is an Interface Class. No data and everything pure virtual
class Shape {
virtual
void Area(int length, int breadth) = 0;
virtual
void Perimeter(int length, int breadth) = 0;
//Note, no data
};

//Derived class - Inherits Shape as Public
class Rectangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


//Derived class - Inherits Shape as Public
class Triangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


int
main()
{

Rectangle r;
Triangle t;

cout<<"\n\n";
r.Area(3,4);
r.Perimeter(3,4);

t.Area(3,4);
t.Perimeter(3,4);

cout<<"\n\n";
return
0;
}


void
Rectangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)<<endl;
}


void
Rectangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<2 * (length + breadth)<<endl;
}


void
Triangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/2<<endl;
}


void
Triangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/3<<endl;
}



In the above example, Shape class is an 'abstract class'. All the interfaces are 'pure interfaces'. It contains no data. The derived classes now have to define the interace functions.

Output:
The Area of Rectangle for length = 3 and breadth = 4 is 12.
The Perimeter of Rectangle for length = 3 and breadth = 4 is 14
The Area of Triangle for length = 3 and breadth = 4 is 6
The Perimeter of Triangle for length = 3 and breadth = 4 is 4


Difference between Abstract class and Interface.
1).Interface have only signature. whereas Abstract class have signature and definition both r allow.
2). Interface have not allow modifier access. whereas Abstract class are allowed modifier access.
3).Thurogh the Interface we can create the Multiple Inheritance whereas Abstract class are not allow the Multiple Inheritance.
4).Interface is slower compare Abstract class.

Reference: Interface Entity vs. Abstract class can refer code project's article.

source:
MSDN
Advance C++ blog
Interview Corner


Read more...

Polymorphism

Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" or is characterized by the phrase "one interface, multiple methods." and it has two distinct aspects:

At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.

Base classes may define and implement virtualmethods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.


Virtual methods enable you to work with groups of related objects in a uniform way. For example, suppose you have a drawing application that enables a user to create various kinds of shapes on a drawing surface. You do not know at compile time which specific types of shapes the user will create. However, the application has to keep track of all the various types of shapes that are created, and it has to update them in response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:
Create a class hierarchy in which each specific shape class derives from a common base class.
Use a virtual method to invoke the appropriate method on any derived class through a single call to the base class method.
First, create a base class called Shape, and derived classes such as Rectangle, Circle, and Triangle. Give the Shape class a virtual method called Draw, and override it in each derived class to draw the particular shape that the class represents. Create a List object and add a Circle, Triangle and Rectangle to it. To update the drawing surface, use a foreach loop to iterate through the list and call the Draw method on each Shape object in the list. Even though each object in the list has a declared type of Shape, it is the run-time type (the overridden version of the method in each derived class) that will be invoked.


public class Shape
{

// A few example members
public int X { get; private set; }
public
int Y { get; private set; }
public
int Height { get; set; }
public
int Width { get; set; }

// Virtual method
public virtual void Draw()
{

Console.WriteLine("Performing base class drawing tasks");
}
}


class
Circle : Shape
{

public
override void Draw()
{

// Code to draw a circle...
Console.WriteLine("Drawing a circle");
base.Draw();
}
}

class
Rectangle : Shape
{

public
override void Draw()
{

// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}

class
Triangle : Shape
{

public
override void Draw()
{

// Code to draw a triangle...
Console.WriteLine("Drawing a triangle");
base.Draw();
}
}


class
Program
{

static
void Main(string[] args)
{

// Polymorphism at work #1: a Rectangle, Triangle and Circle
// can all be used whereever a Shape is expected. No cast is
// required because an implicit conversion exists from a derived
// class to its base class.
System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());

// Polymorphism at work #2: the virtual method Draw is
// invoked on each of the derived classes, not the base class.
foreach (Shape s in shapes)
{

s.Draw();
}


// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}

}




Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks



Read more...

Tuesday, April 20, 2010

Pointer to Function (Alternative to switch-case)

In previous post, we have seen Function pointer. Even though a function is not a variable, it still has a physical location in memory that can be assigned to a pointer. A function's address is the entry point of the function. Because of this, a function pointer can be used to call a function

For example, in an accounting program, you may be presented with a menu that has 20 or more selections.The most common way is to use a switch statement. However, in applications that demand the highest performance, there is a better way. An array of pointers can be created with each pointer in the array containing the address of a function. The selection made by the user is decoded and is used to index into the pointer array, causing the proper function to be executed. This method can be very fast--much faster than the switch method.

However, in applications that demand the highest performance, there is a better way. An array of pointers can be created with each pointer in the array containing the address of a function. The selection made by the user is decoded and is used to index into the pointer array, causing the proper function to be executed. This method can be very fast--much faster than the switch method.


void enter(void), del(void), review(void), quit(void);
int
menu(void);

void
(*options[])(void) = {
enter,
del,
review,
quit
} ;

//Notice how the menu( ) function automatically returns the proper index into the pointer array:
int main(void)
{

int
i;

i = menu(); /* get user's choice */

(*
options[i])(); /* execute it */
return
0;

}


int
menu(void)
{

char
ch;

do
{

printf("1. Enter\n");
printf("2. Delete\n");
printf("3. Review\n");
printf("4. Quit\n");
printf("Select a number: ");
ch = getche();
printf("\n");
}
while(!strchr("1234", ch));
return
ch-49; /* convert to an integer equivalent */
}


void
enter(void)
{

printf("In enter.");
}


void
del(void)
{

printf("In del.");
}


void
review(void)
{

printf("In review.");
}


void
quit(void)
{

printf("In quit.");
exit(0);
}



The program works like this. The menu is displayed, and the user enters the number of the selection desired. Since the number is in ASCII, 49 (the decimal value of 0) is subtracted from it in order to convert it into a binary integer. This value is then returned to main( ) and is used as an index to options, the array of function pointers. Next, the call to the proper function is executed.

Using arrays of function pointers is very common, not only in interpreters and compilers but also in database programs, because often these programs provide a large number of options and efficiency is important.

Source: C++ Complete Reference.

Read more...

Function Pointer

A function pointer is a variable that stores the address of a function that can later be called through that function pointer.
function pointers is setting up "listener" or "callback" functions that are invoked when a particular event happens. The function is called, and this notifies your code that something of interest has taken place.

Why would you ever write code with callback functions? You often see it when writing code using someone's library. One example is when you're writing code for a a graphical user interface (GUI). Most of the time, the user will interact with a loop that allows the mouse pointer to move and that redraws the interface. Sometimes, however, the user will click on a button or enter text into a field. These operations are "events" that may require a response that your program needs to handle. How can your code know what's happening? Using Callback functions! The user's click should cause the interface to call a function that you wrote to handle the event.

To get a sense for when you might do this, consider what might happen if you were using a GUI library that had a "create_button" function. It might take the location where a button should appear on the screen, the text of the button, and a function to call when the button is clicked. Assuming for the moment that C (and C++) had a generic "function pointer" type called function, this might look like this:


void create_button( int x, int y, const char *text, function callback_func );



Whenever the button is clicked, callback_func will be invoked. Exactly what callback_func does depends on the button; this is why allowing the create_button function to take a function pointer is useful.


#include <stdio.h>
void my_int_func(int x)
{

printf( "%d\n", x );
}


int
main()
{

void
(*foo)(int);
/* the ampersand is actually optional */

foo = &my_int_func;

/* call my_int_func (note that you do not need to write (*foo)(2) ) */

foo( 2 );
/* but if you want to, you may */

(*
foo)( 2 );

return
0;
}

Example of check numeric value using function pointer.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

void
check(char *a, char *b, int (*cmp) (const char *,
const
char *));


int
numcmp(const char *a, const char *b);

int
main(void)
{

char
s1[80], s2[80];
gets(s1);
gets(s2);

if
(isalpha(*s1))
check(s1, s2, strcmp);
else

check(s1, s2, numcmp);

return
0;
}


void
check(char *a, char *b, int (*cmp) (const char *,
const
char *))
{

printf("Testing for equality.\n");
if
(!(*cmp) (a, b)) printf("Equal");
else
printf("Not equal");
}


int
numcmp(const char *a, const char *b)
{

if
(atoi(a)==atoi(b)) return 0;
else return
1;
}





You can often avoid the need for explicit function pointers by using virtual functions. For instance, you could write a sorting routine that takes a pointer to a class that provides a virtual function called compare:

Benefits of Function Pointers
Function pointers provide a way of passing around instructions for how to do something
You can write flexible functions and libraries that allow the programmer to choose behavior by passing function pointers as arguments
This flexibility can also be achieved by using classes with virtual functions

References:
1) http://www.cprogramming.com/tutorial/function-pointers.html
2) C++ reference fourth edition
3) MSDN


Read more...

Monday, April 19, 2010

Storage Class Specifier

What is storage class specifer?

There are four storage class specifiers supported by C. They are
extern
static
register
auto

These tell the compiler how the variable that follows should be stored.

extern variable:

Because C allows separately compiled modules of a large program to be linked together to speed up compilation and aid in the management of large projects, there must be some way of telling all the files about the global variables required by the program. The solution is to declare all of your globals in one file and use extern declarations in the other


extern statements are declarations, but not definitions. They simply tell the compiler that a definition exists elsewhere in the program.



File 1:

int
x,y;

void
fun1()
{

x = 22;
}
File 2:

extern
int x,y;

void
fun2()
{

y = x/2;
}

Although extern variable declarations can occur inside the same file as the global declaration, they are not necessary. If the C compiler encounters a variable that has not been declared, the compiler checks whether it matches any of the global variables. If it does, the compiler assumes that the global variable is the one being referenced.

static variable:
static local variable.
When static is applied to a local variable it causes the compiler to create permanent storage for it in much the same way that it does for a global variable.
When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.


// static1.cpp
#include
using namespace std;
void
showstat( int curr )
{

static
int nStatic; // Value of nStatic is retained // between each function call
nStatic += curr;
cout "nStatic is " << nStatic << endl;
}

int
main()
{

for
( int i = 0; i < 5; i++ )
showstat( i );
}

output:
nStatic is 0
nStatic is 1
nStatic is 3
nStatic is 6
nStatic is 10


static global variable:
When the specifier static is applied to a global variable, it instructs the compiler to create a global variable that is known only to the file in which the static global variable is declared.
This means that even though the variable is global, other routines in other files may have no knowledge of it or alter its contents directly;

Register Variable:
The register specifier requests the compiler to store a variable declared with this modifier in a manner that allows the fastest access time possible. For integers and characters, this typically means in the register of the CPU rather than in memory, where normal variables are stored.

In Borland C++, the register specifier may be applied to local variables and to the formal parameters in a function.
You cannot apply register to global variables.
Also, because a register variable may be stored in a register of the CPU, you cannot obtain the address of a register variable. (This restriction applies only to C, and not C++.)

In general, operations on register variables occur much faster than on variables stored in main memory. In fact, when the value of a variable is actually held in the CPU, no memory access is required to determine or modify its value. This makes register variables ideal for loop control.

It is important to understand that the register specifier is just a request to the compiler, which the compiler is free to ignore. However, in general, you can count on at least two register variables of type char or int actually being held in a CPU register for any one function. Additional register variables will be optimized to the best ability of the compiler.

Read more...