Wednesday, June 30, 2010
Sub-Zero Repair Los Angeles
Wednesday, June 23, 2010
Earn from Twitter
How to earn Cash daily through Twitter (PTC)
Hey everyone!
I spent a long time writing this up so I hope you enjoy it. I could have easily sold most of it! I just wanted to share my findings on Twitter as a money making platform. I started this up 9 days ago. Right now I’m not making large profits by any means, but the rate my follow list has grown ensures me that it’ll get better. For the first few days I was getting 20-30 followers and now I’m getting 75-100 each day. This growth makes me feel rather confident.
Now ultimately the most money you could attain from Twitter is using CPA offers. However I’ve also found a PPC service that should generate $20-$50 now and more later.
INTRODUCTION
Now as most of you are aware your Twitter success revolves around followers, thus the more followers the more clicks you’ll get daily. Another user who led me into this left me with this information. “I’m averaging about 600 clicks a day from ten accounts. My largest account has over 5000 followers and my smallest has roughly 2000 followers.” The PPC company pays on average $0.07 per click. However there are many ads that pay 15 cents per click. An ad was released today that says “OMG these shirts are hilarious” and a link after. This ad pays $0.07 cents per click and looks just like any other Twitter post. Many of the ads work this way. You don’t have to worry about looking like a spammer. You’ll look normal and get paid in the process. So here are the steps.
A quick note, after gaining a large follower base you can consider selling ad space on each account. If you had 20,000 followers and sold an ad slot for $10, twice a day, you’d earn $600 per month. Now times this by your 10 accounts. You could also setup your own CPA ads. I think you get the picture.
STEP 1
* Create 10 Twitter accounts
* Ensure that each account has a photo (Using photos of pretty yet believable women works the best.)
* Twitter does not require a valid email to create accounts. Thus you can create 10 accounts in 30 minutes. (I have many backups accounts also. When you reach above 1000 followers you can request to add more than 10 accounts. This will increase your profits rapidly later on.)
STEP 2
* Time to sign up to the PPC affiliate program.
* You do require a PayPal account, but once you earn $100+ you can simply request a check.
* The site to join is RevTwt.com. (Click here to register)
* Another great feature with this site is the ability to use “Auto Post”. The auto posting feature will automatically post up to 3 ads a day on each Twitter account.
* Don’t click on your own ads!!! You will be penalized or completely removed from the program. Every ad has a display link you can follow to review the ad.
* Simply add your 10 Twitter accounts by clicking on the Twitter accounts page.
* You need 50 followers to start posting ads. Don’t worry, you’ll have 50 in a day or two.
STEP 3
* Add followers using a software bot.
* I add roughly 700 followers on each account every night. (Start with just 200-300 for the first few nights, then 500, and make your way to 700)
* I recommend you use the Phoenix Twitter Desktop to automatically follow users.
STEP 4
* Wait 24 hours then clear all the tweets who are not following you back.
* This ensures that you can add 500 people again without being blocked or flagged.
* Currently the best site for clearing out all of the users who have not followed you back is Twitter Karma.
* Don’t forget to follow all of the random users who follow you on their own.
STEP 5
* Set up a controlling platform for all of your accounts.
* It ensures that you look like a real person. I normally post status updates like “Work is boring” or a random fact. The site will update every account at once. (Saving you at least 20 minutes each time)
* The status updates are done through HelloTxt.
* Once you have signed up to this site, add all 10 of your Twitter accounts (Provide full log in details)
* Now you can start posting status updates for all accounts at once.
STEP 6 (Basically rinse and repeat)
* Remember to follow new people every day to increase your followers (Use different search parameters each time. I highly recommend you do not succeed 500 followers a day unless you’re follow count is very high. I’m adding 700 now, but I’m taking a risk with it. Twitter has a technical limit of 2000 per day)
* Bulk remove Tweeters who are not following you back.
* Post realistic updates to your accounts each day. (Bulk update recommended)
My advice regarding this technique
* Stick with it! At first you’ll only see a $1 a day then $5 then $10 etc…. This is a technique that takes roughly a month to reach its peak.
* DON’T SPAM! ONLY ALLOW FOR 3 AUTOMATED AD POSTS EACH DAY
* After you have 5,000+ followers these accounts can be used for CPA marketing and earn even more.
This is a great technique for people who only want to spend 20 minutes a day on creating a reliable stream of income. (It will take a few hours to setup, but it’s easy then after) Post any questions and I’ll try to respond as quickly as possible.
You can bookmark / favorite this post.. Once you have 50 followers, register with RevTwt by CLICKING HERE
Tuesday, June 22, 2010
TCP UDP Difference
Difference between TCP and UDP
| TCP | UDP |
| Reliability: TCP is connection-oriented protocol. When a file or message send it will get delivered unless connections fails. If connection lost, the server will request the lost part. There is no corruption while transferring a message. | Reliability: UDP is connectionless protocol. When you a send a data or message, you don't know if it'll get there, it could get lost on the way. There may be corruption while transferring a message. |
| Ordered: If you send two messages along a connection, one after the other, you know the first message will get there first. You don't have to worry about data arriving in the wrong order. | Ordered: If you send two messages out, you don't know what order they'll arrive in i.e. no ordered |
| Heavyweight: - when the low level parts of the TCP "stream" arrive in the wrong order, resend requests have to be sent, and all the out of sequence parts have to be put back together, so requires a bit of work to piece together. | Lightweight: No ordering of messages, no tracking connections, etc. It's just fire and forget! This means it's a lot quicker, and the network card / OS have to do very little work to translate the data back from the packets. |
| Streaming: Data is read as a "stream," with nothing distinguishing where one packet ends and another begins. There may be multiple packets per read call. | Datagrams: Packets are sent individually and are guaranteed to be whole if they arrive. One packet per one read call. |
| Examples: World Wide Web (Apache TCP port 80), e-mail (SMTP TCP port 25 Postfix MTA), File Transfer Protocol (FTP port 21) and Secure Shell (OpenSSH port 22) etc. | Examples: Domain Name System (DNS UDP port 53), streaming media applications such as IPTV or movies, Voice over IP (VoIP), Trivial File Transfer Protocol (TFTP) and online multiplayer games etc |
RPC in C
RPC Development in C I found the above links very useful. I like you will make use of it.
Execute a Command from another Unix machine
With the above command you can run a particular command from one machine to another machine.
How to write program to run Only one executable in Unix
The following program to make sure that we are running only one instance of a program in Unix :-)
The concept is based on the named key Creation when creating any IPC mechanism.
int main()
{
sem_t *mysem;
mysem = sem_open("MyUniqueName", O_CREAT|O_EXCL);
if ( mysem == NULL )
{
fprintf(stderr, "I am already running!\n");
exit(1);
}
/* the app code here*/
/* end of the app */
sem_unlink("MyUniqueName");
sem_close(mysem);
}
How to write program to run Only one executable in Unix
<code><var style="font-style: normal; color: rgb(0, 0, 176);">The following program to make sure that we are running only one instance of a program in Unix :-)
The concept is based on the named key Creation when creating any IPC mechanism.
int</var> main()
{
sem_t *mysem;
mysem = sem_open(<kbd style="font-style: normal; color: rgb(96, 0, 48);">"MyUniqueName"</kbd>, O_CREAT|O_EXCL);
<var style="font-style: normal; color: rgb(0, 0, 176);">if</var> ( mysem == NULL )
{
fprintf(stderr, <kbd style="font-style: normal; color: rgb(96, 0, 48);">"I am already running!\n"</kbd>);
exit(1);
}
<cite style="font-style: normal; color: rgb(0, 112, 0);">/* the app code here*/</cite>
<cite style="font-style: normal; color: rgb(0, 112, 0);">/* end of the app */</cite>
sem_unlink(<kbd style="font-style: normal; color: rgb(96, 0, 48);">"MyUniqueName"</kbd>);
sem_close(mysem);
}</code>
What operators can/cannot be overloaded?
Most can be overloaded. The only C++ operators that can't be are . and
Buy Projector in SuperStore
Car Buyers Have to visit them :-)
Sunday, June 20, 2010
London's Life the Movie
Saturday, June 19, 2010
Many Algorithms in programs C
1. Reverse a singly linked list
//
// iterative version
//
Node* ReverseList( Node ** List )
{
Node *temp1 = *List;
Node * temp2 = NULL;
Node * temp3 = NULL;
while ( temp1 )
{
*List = temp1; //set the head to last node
temp2= temp1->pNext; // save the next ptr in temp2
temp1->pNext = temp3; // change next to privous
temp3 = temp1;
temp1 = temp2;
}
return *List;
}
2. Delete a node in double linked list
void deleteNode(node *n)
{
node *np = n->prev;
node *nn = n->next;
np->next = n->next;
nn->prev = n->prev;
delete n;
}
3. Sort a linked list
//sorting in descending order
struct node
{
int value;
node* NEXT;
}
//Assume HEAD pointer denotes the first element in the //linked list
// only change the values…don’t have to change the //pointers
Sort( Node *Head)
{
node* first,second,temp;
first= Head;
while(first!=null)
{
second=first->NEXT;
while(second!=null)
{
if(first->value < second->value)
{
temp = new node();
temp->value=first->value;
first->value=second->value;
second->value=temp->value;
delete temp;
}
second=second->NEXT;
}
first=first->NEXT;
}
}
4. Reverse a string
void ReverseString (char *String)
{
char *Begin = String;
char *End = String + strlen(String) - 1;
char TempChar = '\0';
while (Begin < End)
{
TempChar = *Begin;
*Begin = *End;
*End = TempChar;
Begin++;
End--;
}
}
5. Insert a node a sorted linked list
void sortedInsert(Node * head, Node* newNode)
{
Node *current = head;
// traverse the list until you find item bigger the // new node value
//
while (current!= NULL && current->data < newNode->data)
{
current = current->next);
}
//
// insert the new node before the big item
//
newNode->next = current->next;
current = newNode;
}
6. Covert a string to upper case
void ToUpper(char * S)
{
while (*S!=0)
{
*S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
S++;
}
}
7. Multiple a number by 7 without using * and + operator.
NewNum = Num << 3; // mulitplied by 2 ^ 3 = 8
NewNum = NewNum - Num; // 8 – 1 = 7
8. Write a function that takes in a string parameter and checks to see whether or not it is an integer, and if it is then return the integer value.
#include <stdio.h>
int strtoint(char *s)
{
int index = 0, flag = 0;
while( *(s+index) != '\0')
{
if( (*(s + index) >= '0') &&
*(s + index) <= '9')
{
flag = 1;
index++;
}
else
{
flag = 0;
break;
}
}
if( flag == 1 )
return atoi(s);
else
return 0;
}
main()
{
printf("%d",strtoint("0123"));
printf("\n%d",strtoint("0123ii"));
}
9. Print a data from a binary tree – In-order(ascending)
//
// recursive version
//
Void PrintTree ( struct * node node )
{
if ( node == NULL )
return;
PrintTree(node->left );
Printf(“%d”, node->data);
PrintTree(node->right );
}
10. print integer using only putchar
//
// recursive version
//
void PrintNum ( int Num )
{
if ( Num == 0 )
return;
PrintNum ( Num / 10 );
Puthcar ( ‘0’+ Num % 10 );
}
11. Find the factorial of number
//
// recursive version
//
int Factorial( int Num )
{
If ( num > 0 )
return Num * Factorial ( Num –1 );
else
return 1;
}
//
// iterative version
//
int Factorial( int Num )
{
int I
int result = 1;
for ( I= Num; I > 0; I-- )
{
result = result * I;
}
return result;
}
12. Generate Fib numbers:
int fib( n ) // recursive version
{
if ( n < 2 )
return 1;
else
return fib ( n –1 ) + fib ( n –2 );
}
int fib( n ) //iterative version
{
int f1 =1, f2 = 1;
if ( n < 2 )
return 1;
for ( i = 1; i < N; i++)
{
f = f1 + f2;
f1= f2;
f = f1;
}
return f;
}
13. Write a function that finds the last instance of a character in a string
char *lastchar(char *String, char ch)
{
char *pStr = NULL;
// traverse the entire string
while( * String ++ != NULL )
{
if( *String == ch )
pStr = String;
}
return pStr;
}
14. Return Nth the node from the end of the linked list in one pass.
Node * GetNthNode ( Node* Head , int NthNode )
{
Node * pNthNode = NULL;
Node * pTempNode = NULL;
int nCurrentElement = 0;
for ( pTempNode = Head; pTempNode != NULL; pTempNode = pTempNode->pNext )
{
nCurrentElement++;
if ( nCurrentElement - NthNode == 0 )
{
pNthNode = Head;
}
else
if ( nCurrentElement - NthNode > 0)
{
pNthNode = pNthNode ->pNext;
}
}
if (pNthNode )
{
return pNthNode;
}
else
return NULL;
}
15. Counting set bits in a number.
First version:
int CoutSetBits(int Num)
{
for(int count=0; Num; Num >>= 1)
{
if (Num & 1)
count++;
}
return count;
}
Optimized version:
int CoutSetBits(int Num)
{
for(int count =0; Num; count++)
{
Num &= Num -1;
}
}
Reverse a Linkedlist in recursion
{
lnode *temp;
temp=l->first;
while(temp->next != NULL)
{
temp=temp->next;
}
while(temp !=NULL)
{
printf("%d",temp->info);
temp=temp->prev;
}
}
/* Reverse linked list by recursion */
if(head)
head = _ReverseLinkedList(NULL, head, head->next);
NodeStr *_ReverseLinkedList(
NodeStr *preNode,
NodeStr *node1,
NodeStr *node2
)
{
NodeStr *next_node;
if(!node2)
return node1;
next_node = node2->next;
node2->next = node1;
node1->next = preNode;
return _ReverseLinkedList(node1, node2, next_node);
}
Reverse a Linked List Program
#include<stdio.h>
#include<stdlib.h>
struct list
{
int month;
struct list *next;
};
typedef struct list node;
void init(node* record)
{
record->next=NULL;
}
void addnode(node* record,int d)
{
node* fresh;
fresh=(node *)malloc(sizeof(node));
fresh->month=d;
fresh->next=record->next;
record->next=fresh;
}
void print(node *record)
{
node* temp;
temp=(node *)malloc(sizeof(node));
for(temp=record->next;temp;temp=temp->next)
printf(" %d",temp->month);
}
void reverse(node* record)
{
node* temp;node* temp1;node* temp2;
temp=(node *)malloc(sizeof(node));
temp1=(node *)malloc(sizeof(node));
temp2=(node *)malloc(sizeof(node));
temp=record;temp1=temp->next;temp2=temp1->next;
temp->next->next=NULL;
while(temp2!=NULL)
{
temp=temp1;
temp1=temp2;
temp2=temp1->next;
temp1->next=temp;
}
record->next=temp1;
}
int main(void)
{
node* start;
node* start1;
start=(node *) malloc(sizeof(node));
init(start);
int i=0;
for(i=10;i>=0;i--)
addnode(start,i);
print(start);
reverse(start);
printf("n");
print(start);
return 0;
}
Friday, June 18, 2010
Friend Function an Example
class exforsys
{
private:
int a,b;
public:
void test()
{
a=100;
b=200;
}
friend int compute(exforsys e1)
//Friend Function Declaration with keyword friend and with the object of class exforsys to which it is friend passed to it
};
int compute(exforsys e1)
{
//Friend Function Definition which has access to private data
return int(e1.a+e2.b)-5;
}
main()
{
exforsys e;
e.test();
cout<<"The result is:"<
//Calling of Friend Function with object as argument.
}
Thursday, June 17, 2010
Virtual Base Class How To?
Virtual base class is a base class acts as an indirect base
for more than one without duplication of its data members.
A single copy of its data members is shared by all the base
classes that use it as a virtual base.
For example:
A
/ \
B C
\ /
D
class A { /* ... */ }; // indirect base class
class B : virtual public A { /* ... */ };
class C : virtual public A { /* ... */ };
class D : public B, public C { /* ... */ }; // valid
Using the keyword virtual in this example ensures that an
object of class D inherits only one subobject of class A.
Friday, June 4, 2010
C++ Object Slicing
Class Base
{
public:
int i;
};
class Derived : public Base
{
public:
int j;
};
int main()
{
Base Bobj;
Derived Dobj;
Bobj = Dobj; //Here Dobj contains both i and j.
//But only i is copied to Bobj.
}
Thursday, June 3, 2010
How Function Calls Works - A Deep Analysis
This is the first time am peeking into low-level of programming. This topic is not part of my curriculum but had to explore this in order to understand few advanced features of functional programming language. I’ll detail about those features in my future blog.
Function, is just a piece of code which can be referred using a name. The computer stores the data of the function (such as arguments, local variables, return address etc.,) when a function is invoked and destroys them when the function returns. Similarly when a function calls other functions, the caller function returns only after all the callee functions are returned. We can infer a LIFO (last-in-first-out) scenario in this, ie., the function that is invoked last completes first and the one invoked first completes last. So the stack becomes an obvious choice for function calls implementation.
In the memory, the stack grows from the higher memory address to the lower memory addresses. So we have to visualize an inverted stack. Have look at the below diagram.
Let me brief through all the terminologies before we get into the working.
Stack frame – The section of memory where the local variables, arguments, return address and other information of a function are stored, is called stack frame or activation record.
Stack pointer – For function calls, a bulk of data is pushed and popped from the memory, whenever a function is invoked and returned respectively. But we may need to access the data which is deep into the stack and it will be inefficient to pop off all the data to do that. Hence, unlike conventional stack implementation, we have a register called stack pointer that points to top of the stack such that all the addresses smaller than the address to which the stack pointer points are considered as garbage and all the address larger are considered as valid.
Stack bottom – It is the highest valid address of the stack. When the stack is initialized the stack pointer points to stack bottom.
Stack limit – It is the smallest valid address of the stack. When the stack pointer goes below this address, then there’s stack overflow.
Frame pointer – When a new function is invoked the frame pointer points to where the stack pointer was and when the function returns the stack pointer points back to where the frame pointer is.
Return address – It points to address (within the caller function) to which the control should pass when the callee (current) function returns.
Static link – This comes into picture for the programming languages that support nested functions. When a function (nested function) is defined within another function (enclosing function), the nested function may need to access the variables of the enclosing function. Therefore, the nested function’s stack frame should be able to access the enclosing function’s frame. This made possible by static link which points to the address of the enclosing function’s frame.
How it works?
The working of stack differs with different programming languages. Programming languages like C, doesn’t support nested functions and they dont need static link. Programming lanuages like Pascal support nested functions and they use static link. There are programming languages like ML and Scheme which support both nested functions and function-valued variables (ie., a function returned as a result of another function). I am not aware of how these function calls work. I have discussed the working only for programming languages that support nested functions.
Consider a pseudo-C code: (This doesn’t work in C. Just using a comfortable syntax.)
int foo (int arg1)
{
int f (int arg2)
{
int i=10;
return arg2 * i;
}
int g(int arg3)
{
return f(arg3);
}
return g(arg1);
}
f and g are nested functions of foo. foo invokes g which inturn invokes f.
![]()
Stack frame – working
When the function foo invokes function g, the argument arg3 is pushed into the stack. A new section memory is allocated for the function g and the stack pointer points to the highest unused address. The frame pointer points to where stack pointer was. The old frame pointer is pushed ie., 1. The static link which points to the address of the enclosing function foo is pushed, ie., 1. The return address is pushed ie., to foo.
Then when the function f is invoked the argument arg2 is pushed. Now the frame pointer points to where the stack pointer was. The old FP is pushed ie., 3. The static link pointing to foo is pushed ie., 1. The return address is pushed ie., to g. Then the local variable i is pushed.
When the function f returns. The stack pointer points to where stack pointer was and the frame pointer points to the address stored as old FP in f’s stack frame.
This simply doesn’t work with languages like ML and scheme because in those, the local variables should not be destroyed while the function returns! as they may be required for the nested callee function.
How recursive functions work?
The recursive functions work in same way as the other functions. For every recursive call a new stack frame of the function is created. But this avoided in tail recursive calls in functional languages. In tail recursive call, each recursive call is made to loop to the same stack frame.
Stack overflow
When the stack pointer goes below the stack limit, then there’s stack overflow. The most common cause for stack overflow is the infinite loop in the recursive function calls. Imagine if a function is invoked recursively for infinite times, a stack frame gets appended for every recursive call and at one point the stack pointer goes below the stack limit and thus a stack overflow is caused.
Stack Vs Heap - Memory Management in C
As well you can also find the memory management in C.
http://net.pku.edu.cn/~course/cs101/2008/resource/heapAndStack.html
IBM C++ tutorial... Very informative
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr155.htm
C++ exceptions from a destructor - Dont USE
Stack unwinding (C++ only)
Stack unwinding (C++ only)
When an exception is thrown and control passes from a try block to a handler, the C++ run time calls destructors for all automatic objects constructed since the beginning of the try block. This process is called stack unwinding. The automatic objects are destroyed in reverse order of their construction. (Automatic objects are local objects that have been declared auto or register, or not declared static or extern. An automatic object x is deleted whenever the program exits the block in which x is declared.)
#include <iostream>using namespace std;
struct E {
const char* message;
E(const char* arg) : message(arg) { }
};
void my_terminate() {
cout << "Call to my_terminate" << endl;
};
struct A {
A() { cout << "In constructor of A" << endl; }
~A() {
cout << "In destructor of A" << endl;
throw E("Exception thrown in ~A()");
}
};
struct B {
B() { cout << "In constructor of B" << endl; }
~B() { cout << "In destructor of B" << endl; }
};
int main() {
set_terminate(my_terminate);
try {
cout << "In try block" << endl;
A a;
B b;
throw("Exception thrown in try block of main()");
}
catch (const char* e) {
cout << "Exception: " << e << endl;
}
catch (...) {
cout << "Some exception caught in main()" << endl;
}
cout << "Resume execution of main()" << endl;
}
The following is the output of the above example:
In try block
In constructor of A
In constructor of B
In destructor of B
In destructor of A
Call to my_terminate
In the try block, two automatic objects are created: a and b. The try block throws an exception of type const char*. The handler catch (const char* e) catches this exception. The C++ run time unwinds the stack, calling the destructors for a and b in reverse order of their construction. The destructor for a throws an exception. Since there is no handler in the program that can handle this exception, the C++ run time calls terminate(). (The function terminate() calls the function specified as the argument to set_terminate(). In this example, terminate() has been specified to call my_terminate().)
How to generate Alignment error in C - Padding
#pragma pack (1)
struct s {
char c; // offset 0
int i; // offset 1!
} ss;
#pragma pack ()
void f_improper(int *p)
{
*p = 23; // generates a fault
}
void g_proper(int __unaligned *p) // OK
{
*p = 42;
}
void main ()
{
f_improper(&ss.i);
g_proper(&ss.i);
}
How to avoid structure padding in C?
for ex
typedef struct s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
} s;
Size of this structure is of 11 Bytes. but due to default
byte alignment(8 byte) which is different for different
compilers. The size of structure would be 16 Bytes.
In order to change the alignment, we will have to do
something like this.
#pragma pack(1)
typedef struct s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
//unsigned char b;
} s;
#pragma pack()
This will change the byte alignment to 1 Byte. and thus size of structure will be exactly 11 bytes
#include
int x;
int x=10;
#pragma pack(1)
struct testpad
{
int i;
unsigned char c;
} pad;
#pragma pack()
struct test
{
int i;
unsigned char c;
} s;
int main()
{
printf("X:%d WITHOUT PAD:%d, WITH PAD:%d\r\n",x,sizeof(s), sizeof(pad) );
return 0;
}
O/p: X:10 WITHOUT PAD:8, WITH PAD:5
Structure padding - Memory alignment
alignment is
called structure padding.
It can be explained with a simple example...... (Under UNIX machine)
struct X
{
char ch;
int i;
char a ;
char b;
long l;
};
How the structure is padded is explained below.....
First the compiler allots a 4-byte location to the char variable ch.
Since ch occupies only
one byte the remaining 3 bytes are left unused. Now the compiler checks
whether the
next variable i.e (int i) can be inserted in the unused space. Since int
occupies 4 bytes
it can't be inserted in the available space of 3 bytes.. So what the
compiler does is it
pads the 3 unused bytes with some unknown names....
Now the memory of 4 bytes will be allocated to int i. After
this, the compiler assigns a 4-byte location to char a. Since char
occupies only one byte 3 bytes are left
unused. Now the compiler checks whether the next variable can be
inserted in the left over space. Since the next variable is a char ,
which can be fit in the left over space.
Thus a 2-byte location is padded... Hope the concept is clear.....
Wednesday, June 2, 2010
C++ Copy constructor
When copies of objects are made
A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).
A variable is declared which is initialized from another object, eg,
Person q("Mickey"); // constructor is used to build q.
Person r(p); // copy constructor is used to build r.
Person p = q; // copy constructor is used to initialize in declaration.
p = q; // Assignment operator, no constructor or copy constructor.
A value parameter is initialized from its corresponding argument.
f(p); // copy constructor initializes formal value parameter.
An object is returned by a function.
C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes a shallow copy.
Don't write a copy constructor if shallow copies are ok
If the object has no pointers to dynamically allocated memory, a shallow copy is probably sufficient. Therefore the default copy constructor, default assignment operator, and default destructor are ok and you don't need to write your own.
If you need a copy constructor, you also need a destructor and operator=
If you need a copy constructor, it's because you need something like a deep copy, or some other management of resources. Thus is is almost certain that you will need a destructor and override the assignment operator.
Copy constructor syntax
The copy constructor takes a reference to a const parameter. It is const to guarantee that the copy constructor doesn't change it, and it is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which ...
Here is an example of a copy constructor for the Point class, which doesn't really need one because the default copy constructor's action of copying fields would work fine, but it shows how it works.
//=== file Point.h =============================================
class Point {
public:
. . .
Point(const Point& p); // copy constructor
. . .
//=== file Point.cpp ==========================================
. . .
Point::Point(const Point& p) {
x = p.x;
y = p.y;
}
. . .
//=== file my_program.cpp ====================================
. . .
Point p; // calls default constructor
Point s = p; // calls copy constructor.
p = s; // assignment, not copy constructor.
Difference between copy constructor and assignment
A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but it is somewhat simpler:
There is no need to test to see if it is being initialized from itself.
There is no need to clean up (eg, delete) an existing value (there is none).
A reference to itself is not returned.
Unaddressed issue
[Question: When is the base (parent) class copy constructor called? Is it like Java and the parent constructor is called at the beginning of each constructor? Does it have to be explicit?]
Reverse a Linked List in C Function
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}
else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0;
cur->next = head;
for(; curnext!=0; )
{
cur->next = pre;
pre = cur;
cur = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}
Deep Copy Shalow Copy Difference in C++
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack. If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.
Ways to Create Deep Copy - using Constructors
a constructor function with the same name as the class
used to make deep copy of objects.
There are 3 important places where a copy constructor is called.
When an object is created from another object of the same type
When an object is passed by value as a parameter to a function
When an object is returned from a function
If a copy constructor is not defined in a class, the compiler itself defines one. This will ensure a shallow copy. If the class does not have pointer variables with dynamically allocated memory, then one need not worry about defining a copy constructor. It can be left to the compiler's discretion.
But if the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor.
For ex:
class A //Without copy constructor
{
private:
int x;
public:
A() {A = 10;}
~A() {}
}
class B //With copy constructor
{
private:
char *name;
public:
B()
{
name = new char[20];
}
~B()
{
delete name[];
}
//Copy constructor
B(const B &b)
{
name = new char[20];
strcpy(name, b.name);
}
};
Let us Imagine if you don't have a copy constructor for the class B. At the first place, if an object is created from some existing object, we cannot be sure that the memory is allocated. Also, if the memory is deleted in destructor, the delete operator might be called twice for the same memory location.
This is a major risk. One happy thing is, if the class is not so complex this will come to the fore during development itself. But if the class is very complicated, then these kind of errors will be difficult to track.
Pointers Differed from References
References may not be null.
Say you are writing a function and you know that you do not wish an argument to be an object of type T.
That leaves you with two choices. The argument can be a pointer to T or a reference to T.
If it is acceptable for the caller of the function to pass nothing, either because he has nothing or because nothing can be used to indicate special processing, then use a pointer because it can be initialized with a null value.
If it is not acceptable for the caller of the function to pass nothing, then use a reference because it cannot be initialized with a null value.
Enforce contracts at compile-time rather than at run-time wherever possible.
I have been looking at another object-oriented programming language as of late and one of the things I don't like about it is that it only allows access to objects through its version of references in a world where a reference can always refer to nothing. Thus much of the code I have seen is littered with statements such as (if ref!=null) or the code just throws exceptions at run-time if a null reference is used.
IMHO the C++ methods for accessing objects indirectly are more diverse than this other language and the slight difference between pointers and references in C++ allow the programmer to communicate intent to fellow programmers with
the advantage of support of the compiler.
C++ Pointers Vs References
Consider the following code:
Pointers References
int i; int i;
int *pi = &i; int &ri = i;
In both cases the situation is as follows:
Both pi and ri contain addresses that point to the location of i, but the difference lies in
the appearance between references and pointers when they are used in expressions. In
order to assign a value of 4 to i in both cases, we write:
*pi = 4; ri = 4;
Note the, when using pointers, the address must be dereferenced using the *, whereas,
when using references, the address is dereferenced without using any operators at all!
The main effect of this is that the address can directly be manipulated if it is a pointer.
We can do things such as:
pi++;
to increment to the next address. This is not possible using references. Therefore, to
summarize, a pointer can point to many different objects during its lifetime, a reference
can refer to only one object during its lifetime.
When to Use Pointers vs References
References are the preferred way of indirectly accessing a variable. They are also a little
safer than pointers and, in some cases, are the only way to achieve a particular result such
as overloading certain operators. Consider the following:
enum day
{
Sunday, Monday, ...
};
If we define a variable;
day x;
pi
i
ri
addr
addr addr
and we wanted to write a method to overload the ++ operator such that the statement
++x;
increments x to the next day, we could write the following:
day &operator++(day &d)
{
d = (day)(d + 1);
return d;
}
Using pointers, we may think that the following declaration would work:
day *operator++(day *d);
However, this statement will not even compile because every overloaded operator
function must either be a member of a class, or have a parameter of type T, T &, or T
const &, where T is a class or enumeration type. So in this particular case, using a
reference is the only way to do it.
Classes Vs Structures in C++
1) Classes are inherited as private by default, structures are inherited as publicly.
2) Classes members are private by, structures members are public as default
| Classes | Structures |
| Members are Private | Members are Public |
| Inherited Privately | Inherited Publically |
Fork Program in C
int main(){
int i=10;
if(fork() == 0){
i=i+5;
printf("Child---%d\n",i);} else {i=i-5;
printf("Parent---%d\n",i);
}}
Tuesday, June 1, 2010
If your Mind Works you can solve
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOCOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
2- If you already found the C, now find the 6 below.
99999999999999999999999999999999999999999999999
99999999999999999999999999999999999999999999999
99999999999999999999999999999999999999999999999
69999999999999999999999999999999999999999999999
99999999999999999999999999999999999999999999999
99999999999999999999999999999999999999999999999
3 - Now find the N below. It's a little more difficult.
MMMMMMMMMMMMMMMMMMMMMMMMMMMMNMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
This is NOT a joke. If you were able to pass these three tests, you can cancel your annual visit to your neurologist. Your brain is great and you're far from having a close relationship with Mr Alzheimer.
Eonvrye whocan raed this rsaie your hnad.
To my 'selected' strange-minded friends:
If you can read the following paragraph, forward it on to your friends and the person that sent it to you with 'yes' in the subject line... Only great minds can read this
This is weird, but interesting!
If you can raed this, you have a sgtrane mnid too
Can you raed this? Olny 55 plepoe out of 100 can.
I cdnuolt blveiee that I cluod aulaclty uesdnatnrd what I was rdanieg. The phaonmneal pweor of the hmuan mnid, aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it dseno't mtaetr in what oerdr the ltteres in a word are, the olny iproamtnt tihng is that the frsit and last ltteer be in the rghit pclae. The rset can be a taotl mses and you can still raed it whotuit a pboerlm. This is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the word as a wlohe. Azanmig huh? Yaeh and I awlyas tghuhot slpeling was ipmorantt! If you can raed this forwrad it
FORWARD ONLY IF YOU CAN READ IT


