/*----------------------------------------------------- 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...