Showing posts with label operators. Show all posts
Showing posts with label operators. Show all posts

How Bitwise Operators are Used, an Example Program

Well, one-by-one we’ve discussed each of the Bitwise
Operator
. Starting from Operation
on Bits and Bitwise Operators
, we moved on to Right/Left
Bit Shift Operators
then discussed Decimal
Number to Binary Conversion Program
. and at last One's
Complement and XOR Operators
. After having so much theoretical it’s
time now for a nice Example Program, which is the topic of today’s post.
The code here is basically to show how these bitwise operator are used rather
than what they are used for.



// Example Program to demonstrate how
// One's Complement (~) and XOR (^)
// Opeartors are used.
#include<stdio.h>

// prototype
void showbits(short int);

// defined
void showbits(short int dec_num)
{
short int loop, bit, and_mask;

for(loop=15; loop>=0; loop--)
{
and_mask=1<<loop;
bit=dec_num&and_mask;


if(bit==0) printf("0");
else printf("1");
}
}

void main()
{
// declare three short ints
// for storing user inputs
// and results
short int a,b,res;
int ch;

while(ch!=7)
{
// show main menu
printf("\t\tMain Menu\n");
printf("\t\t---------\n");
printf("1. Perform Left Bit Shift Operation\n");
printf("2. Perform Right Bit Shift Operation\n");
printf("3. Perform AND Operation\n");
printf("4. Perform OR Operation\n");
printf("5. Perform One's Complement Operation\n");
printf("6. Perform XOR Operation\n");
printf("7. Quit\n");
scanf("%d",&ch);

switch(ch)
{
case 1:
// take input
printf("\n\nEnter a decimal number: ");
scanf("%d",&a);
printf("\nEnter number of places to shift bit: ");
scanf("%d",&b);


printf("\n\n\tEntered Number: ");
showbits(a);
printf(" (decimal %d)",a);

// perform left bit shift
// operation
res=a<<b;

// show the formatted output
printf("\n\tLeft Shifted : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;

case 2:
// take input
printf("\n\nEnter a decimal number: ");
scanf("%d",&a);
printf("\nEnter number of places to shift bit: ");
scanf("%d",&b);


printf("\n\n\tEntered Number: ");
showbits(a);
printf(" (decimal %d)",a);

// perform right bit shift
// operation
res=a>>b;

// show the formatted output
printf("\n\tRight Shifted : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;

case 3:
printf("\n\nEnter two decimal number: ");
scanf("%d",&a);
scanf("%d",&b);

printf("\n\n\tEntered Number 1: ");
showbits(a);
printf(" (decimal %d)",a);
printf("\n\tEntered Number 2: ");
showbits(b);
printf(" (decimal %d)",b);

// perform AND operation on two
// variables a and b
res=a&b;

printf("\n\tAND'ed : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;

case 4:
printf("\n\nEnter two decimal number: ");
scanf("%d",&a);
scanf("%d",&b);

printf("\n\n\tEntered Number 1: ");
showbits(a);
printf(" (decimal %d)",a);
printf("\n\tEntered Number 2: ");
showbits(b);
printf(" (decimal %d)",b);

// perform OR operation on two
// variables a and b
res=a|b;

printf("\n\tOR'ed : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;

case 5:
// take input
printf("\n\nEnter a decimal number: ");
scanf("%d",&a);

printf("\n\n\tEntered Number: ");
showbits(a);
printf(" (decimal %d)",a);

// perform one's complement
// operation
res=~a;

// show the formatted output
printf("\n\t~'ed : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;

case 6:
printf("\n\nEnter two decimal number: ");
scanf("%d",&a);
scanf("%d",&b);

printf("\n\n\tEntered Number 1: ");
showbits(a);
printf(" (decimal %d)",a);
printf("\n\tEntered Number 2: ");
showbits(b);
printf(" (decimal %d)",b);

// perform XOR operation on two
// variables a and b
res=a^b;

printf("\n\tXOR'ed : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;

}
}
}


Test Run:


   Main Menu
---------
1. Perform Left Bit Shift Operation
2. Perform Right Bit Shift Operation
3. Perform AND Operation
4. Perform OR Operation
5. Perform One's Complement Operation
6. Perform XOR Operation
7. Quit
1


Enter a decimal number: 3476
Enter number of places to shift bit: 3


Entered Number: 0000110110010100 (decimal 3476)
Left Shifted : 0110110010100000 (decimal 27808)

   Main Menu
---------
1. Perform Left Bit Shift Operation
2. Perform Right Bit Shift Operation
3. Perform AND Operation
4. Perform OR Operation
5. Perform One's Complement Operation
6. Perform XOR Operation
7. Quit
2


Enter a decimal number: 543
Enter number of places to shift bit: 5


Entered Number: 0000001000011111 (decimal 543)
Right Shifted : 0000000000010000 (decimal 16)

   Main Menu
---------
1. Perform Left Bit Shift Operation
2. Perform Right Bit Shift Operation
3. Perform AND Operation
4. Perform OR Operation
5. Perform One's Complement Operation
6. Perform XOR Operation
7. Quit
7
Press any key to continue...

Related Articles:


One's Complement and XOR Operators

Talking about Bit
Operators
we are left with two of them, which we’ll be discussing
in this article.


One’s Complement Operator (~)


It takes and works only on one operand. On taking one’s complement of
any variable, the 0s are changed to 1 and vice-versa from the bit structure
(binary representation) of that variable. The following example will make it
easier to understand:


Suppose we have a short int a


short int a = 16;


its binary representation will be


0000000000010000 (decimal 16)


on taking one’s complement like below


res = ~a;


res will contain


1111111111101111 (decimal 65519)


It can be used as a part of algorithm to encrypt data.


XOR (eXclusive OR) (^)


It is derived from the OR
Operator
and takes two operands to work on. It compares bits like the
OR
bitwise operator
but exclusively for OR cases.


Following will clarify what it does:


short int a = 46265, its binary form


1011010010111001


another short int b = 46734, binary


1011011010001110


performing XOR operation


a -> 1011010010111001

b -> 1011011010001110

XOR'ed-> 0000001000110111


As you can see, it compares two bits (from variable a and
b) and if both are same it gives 0 or 1 in any other case.
Thus we can say it does an eXclusive OR comparison between
the bit structure of two variables.


now let's look at an example code showing how these two operators are used:



// Example Program to demonstrate how
// One's Complement (~) and XOR (^)
// Opeartors are used.
#include<stdio.h>

// prototype
void showbits(short int);

// defined
void showbits(short int dec_num)
{
short int loop, bit, and_mask;

for(loop=15; loop>=0; loop--)
{
and_mask=1<<loop;
bit=dec_num&and_mask;


if(bit==0) printf("0");
else printf("1");
}
}

void main()
{
// declare three short ints
// for storing user inputs
// and results
short int a,b,res;
int ch;

while(ch!=3)
{
// show main menu
printf("\t\tMain Menu\n");
printf("\t\t---------\n");
printf("1. Perform One's Complement Operation\n");
printf("2. Perform XOR Operation\n");
printf("3. Quit\n");
scanf("%d",&ch);

switch(ch)
{
case 1:
// take input
printf("\n\nEnter a decimal number: ");
scanf("%d",&a);

printf("\n\n\tEntered Number: ");
showbits(a);
printf(" (decimal %d)",a);

// perform one's complement
// operation
res=~a;

// show the formatted output
printf("\n\t~'ed : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;
case 2:
printf("\n\nEnter two decimal number: ");
scanf("%d",&a);
scanf("%d",&b);

printf("\n\n\tEntered Number 1: ");
showbits(a);
printf(" (decimal %d)",a);
printf("\n\tEntered Number 2: ");
showbits(b);
printf(" (decimal %d)",b);

// perform XOR on two
// variables a and b
res=a^b;

printf("\n\tXOR'ed : ");
showbits(res);
printf(" (decimal %d)\n\n",res);

break;
}
}
}


Test Run:


   Main Menu
---------
1. Perform One's Complement Operation
2. Perform XOR Operation
3. Quit
1


Enter a decimal number: 37


Entered Number: 0000000000100101 (decimal 37)
~'ed : 1111111111011010 (decimal -38)

   Main Menu
---------
1. Perform One's Complement Operation
2. Perform XOR Operation
3. Quit
2


Enter two decimal number: 987
10


Entered Number 1: 0000001111011011 (decimal 987)
Entered Number 2: 0000000000001010 (decimal 10)
XOR'ed : 0000001111011001 (decimal 985)

 Main Menu
---------
1. Perform One's Complement Operation
2. Perform XOR Operation
3. Quit
3
Press any key to continue...

Related Articles:


Right/Left Bit Shift Operators

This is the continuation of the article Operation
on Bits and Bitwise Operators
.
If you haven’t read that, it is
strongly recommended that you do, before proceeding with this article.


Bit shifting, as the name signifies, does shifting of bits in byte(s). There
are basically two ways, in which bits (of a byte) can be shifted, either to
the right, or to the left. Thus we have two types of bit shifting operator.


If you think logically, its pretty clear that for bit shifting in a byte, we
need to have two data. We need the byte(s) to shift bits on and the number of
bits to be shifted. Guess what, the two operators need these to data as operands!


Right Bit Shifting Operator (>>)



Syntax: res = var >> num;


This would shift all bits in the variable var, num places
to the right which would get stored to the variable res. So
for example if var has the following bit structure:


var = 00110101 (decimal 53)


And we do the following operation:


res = var >> 2;


We would get res as:


res = 00001101 (decimal 13)


As you can see, shifting of the bits to right disposes the bits
(2) from the right and introduces 0s (2) to the left.


Left Bit Shift Operator (<<)



It is similar to the right shift operator except that the direction of shifting
is opposite. The following is I think enough to explain this:


var = 00110101 (decimal 53)


And we do the following operation:


res = var << 2;


We would get res as:


res = 11010100 (decimal 212)


Just the opposite here, here bits get disposed from the left and new 0s are
introduced to the right.


Related Articles:


Operation on Bits and Bitwise Operators

OK guys, this is my first post in the New Year 2008, I thought of posting it
earlier but at last I didn’t. It’s already been so long since I
posted so let’s keep everything aside and talk just about what we have
for today. ;-)


I was sitting the other day thinking about what to write for a post here. Suddenly
I realized that we have discussed operations
on matrices
, arrays,
and what not but we haven’t had the chance to talk anything about the
most fundamental thing a computer understands. Yeah, Operation on Bits.


Bits can have only two values either ON (1) or OFF (0). In this article, we’ll
be discussing about the different operations which can be performed on bits.
One thing to note here is, we don’t perform these operation on single
bits but rather on a group of bits (byte(s)). So even though Bitwise operators
operate on bits its almost always a part of a group (byte, which makes up each
data type), it means we can do bitwise operations on any data type.


BTW, the operators that perform operation on bits are called Bitwise Operator
and such operations are known as Bitwise Operations


The six bitwise operators are listed below:




























&


AND


|


OR


^


XOR


>>


Right shift


<<


Left shift


~


One’s complement


For this post we’ll only be discussing &(AND) and | (OR) operators
leaving the rest for future posts ;-)


Bitwise AND (&) Operator: First thing, it’s nothing to do with the
Logical (&&) operator, both are different.


Now, if you know something about Logic Gates then you might already know about
this. For the rest of us, it does an AND mask on bits.


So, suppose if we have two separate bytes having binary values as 00100000
and 00100001 then doing AND operation would give us the following result.











First Byte:

Second Byte:

00100000

00100001

Result:

00100000

The truth table for this would be:













First Bit
Second Bit
& (AND)

1


1


0


0


1


0


1


0



1


0


0


0



As the Logic AND Gate does, it takes two bits (from the two separate bytes)
and if both of them are ON (1) then only it gives ON (1) in all other cases
it gives OFF (0). So starting from the right there is 0&1->0, 0&0->0,…,
1&1->1 and so on.


Bitwise OR (|) Operator: Here again, both OR (||) and Bitwise OR (|) are different.


The following example is sufficient for you all to understand its operation.











First Byte:

Second Byte:

00100000

00100001

Result:

00100001

Truth table













First Bit
Second Bit
& (OR)

1


1


0


0

1


0


1


0

1


1


1


0


There won’t be any example program here because to fully understand these
operators we need to express data as bits (binary form) and see how the operations
change them. Since decimal to binary conversion programs require some bitwise
operations that we’ve yet to discuss so I think it’ll be pointless
to have such programs now!


P.S. An integer in 32-Bit (Windows) environment is 4 bytes long. Short int
is half of that

8 bits make up one byte.


Related Articles:


Overloading the Parenthesis () Operator

First, I want to apologize to my readers for not being able to post lately,
partly due to me being very busy these days;-)


As we all know, there are certain ways by which we can pass data to objects
(of class). We can pass values during the time of construction as below:


  class-name ob-name(values);

Or we may define a member function to accept data which can be called as below:


  class-name ob-name;
ob-name.set(values);

Where set is the member function of the class.


But actually there is one more way to do so, yeah you guessed it right!, by
overloading the parenthesis () operator.


Parenthesis () operator like other operators is overloaded with the following
prototype:


  ret-type operator()(arg1, arg2,...);


It is a unary operator hence the only argument passed to this function (implicitly)
is this pointer. The argument list may contain any number of arguments as you
wish to pass.


The following example program illustrates the overloading of parenthesis ()
operator in C++.



// Overloading Parenthesis ()
// Operator
#include <iostream.h>

class myclass
{
int a,b;

public:
myclass(){}
myclass(int,int);
myclass operator()(int,int);
void show();
};

// ------------------------
// --- MEMBER FUNCTIONS ---
myclass::myclass(int x, int y)
{
a=x;
b=y;
}

myclass myclass::operator()(int x, int y)
{
a=x;
b=y;

return *this;
}

void myclass::show()
{
cout<<a<<endl<<b<<endl;
}
// --- MEMBER FUNCTIONS ---
// ------------------------

void main()
{
myclass ob1(10,20);
myclass ob2;

ob1.show();

// it's a nice way to pass
// values, otherwise we
// would have to define and
// call a member/friend function
// to do so
ob2(100,200);
ob2.show();
}


Related Articles:


Overloading [] Operator II

In the previous article Overloading
[] Operator
, we overloaded the [] operator in a class to access data
within the class by indexing method.


The operator [] function was defined as below:


  int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

As you can see, the above operator
function
is returning values, hence it could only be used on the right
hand side of a statement. It’s a limitation!


You very well know that a statement like below is very common with respect
to arrays:


a[1]=10;


But as I said, the way we overloaded the [] operator, statement like the one
above is not possible. The good news is, it is very easy to achieve this.


For this we need to overload the [] operator like this:


  int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

By returning a reference
to the particular element, it is possible to use the index expression on the
left hand side of the statement too.


The following program illustrates this:



// Example Program illustrating
// the overloading of [] operator
// ----
// now the index expression can be
// used on the left side too
#include <iostream.h>

class myclass
{
// stores the number of element
int num;
// stores the elements
int a[10];

public:
myclass(int num);

int &operator[](int);
};

// takes the number of element
// to be entered.(<=10)
myclass::myclass(int n)
{
num=n;
for(int i=0;i<num;i++)
{
cout<<"Enter value for element "<<i+1<<":";
cin>>a[i];
}
}

// returns a reference
int &myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];
}

void main()
{
myclass a(2);

cout<<a[0]<<endl;
cout<<a[1]<<endl;

// indexing expression on the
// left-hand side

a[1]=21;
cout<<a[1];
}


Related Articles:


Overloading [] Operator

Have a look at the following code fragment:


  myclass a(3);

cout<<a[0];

Doesn’t it look awkward!


Yes it does, because we have overloaded he [] operator and given it some special
meaning.


In C++, it is possible to overload the [] operator
and give it a different meaning
rather then the usual object indexing.


The general form for overloading [] operator is:


  ret-type operator[](int);

It is considered a binary operator hence when declared as a member, it accepts
one explicit argument (usually int).


Although you are free to accept any type of argument but sticking to the original
concept of indexing, it would always be an integer.


ob[i];


When the compiler encounters the above expression (with the [] operator overloaded)
the [] operator
function
is called as below:


ob.operator[] (1)


The argument ‘1’ is passed explicitly while ‘ob’ is
passed implicitly using the ‘this’
pointer.


Enough discussion, now lets get on to some action!


Below is the example program illustrating the overloading of [] operator:



// Example Program illustrating
// the overloading of [] operator
#include <iostream.h>

class myclass
{
// stores the number of element
int num;
// stores the elements
int a[10];

public:
myclass(int num);

int operator[](int);
};

// takes the number of element
// wished to be entered.(<=10)
myclass::myclass(int n)
{
num=n;
for(int i=0;i<num;i++)
{
cout<<"Enter value for element "<<i+1<<":";
cin>>a[i];
}
}

int myclass::operator[](int index)
{
// if not out of bound
if(index<num)
return a[index];

// else
return NULL;
}

void main()
{
myclass a(3);

cout<<a[0]<<endl;
cout<<a[2]<<endl;

// out of bound
cout<<a[3]<<endl;
}


Related Articles:


Adding Flexibility to Operators while Overloading them

  class_name class_name::operator+(int x)
{
class_name temp;

temp.a = a + x;
temp.b = b + x;

return temp;
}


With reference to the above operator
function
and supposing that ‘ob’ is an object of the class
to which this function belongs; Is the statement below legal:


ob2 = ob1 + 100;


Yes, but what about the following statement:


ob2 = 100 + ob1;


Surely this won’t work!


100 is an integer constant and has no ‘+’ operator that could add
it with user-defined types (object ‘ob’).


This certainly is a shortcoming, since often we don’t really care which
operand is where (as in addition and multiplication) and we order the operands
as necessary (as in subtraction and division).


To overcome this we can overload two-two versions of these operators
as friend
, one for ‘integer + object’ type and the other
for ‘object + integer’ type.


So, for example for addition we have to overload the ‘+’ operator
twice as below:


  friend class_name operator+(class_name,int);
friend class_name operator+(int,class_name);

Similarly we have to overload other operators.


The program below illustrates this concept:



// Program to illustrate
// the overloading of
// flexible addition
// and subtraction
// operators
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// object + int form
friend myclass operator+(myclass,int);
friend myclass operator-(myclass,int);

// int + object form
friend myclass operator+(int,myclass);
friend myclass operator-(int,myclass);
};

myclass operator+(myclass ob,int x)
{
myclass temp;

temp.a = ob.a + x;
temp.b = ob.b + x;

return temp;
}

myclass operator-(myclass ob, int x)
{
myclass temp;

temp.a = ob.a - x;
temp.b = ob.b - x;

return temp;
}

myclass operator+(int x, myclass ob)
{
// does the same thing
// because in addition
// it doesn't matters
// which operand is where
myclass temp;

temp.a = x + ob.a;
temp.b = x + ob.b;

return temp;
}

myclass operator-(int x, myclass ob)
{
myclass temp;

temp.a = x - ob.a;
temp.b = x - ob.b;

return temp;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a=a + 10;
a.show();

b=100 + b;
b.show();
}


Related Articles:


Using Friends to Overload all the Overloaded Arithmetic Operators

In the article Class
with all the Overloaded Arithmetic Operators
, we overloaded (almost)
all the arithmetic operators in one program, similarly in this article we’ll
be overloading them once again but now using friend functions.


We have already overloaded similar operators before (using friend
functions
), so you won’t be having any troubles in understanding
the program below:



// Program that Overloads
// all the arithmetic operators
// using friend functions
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// declared as friend
friend myclass operator+=(myclass&, myclass);
friend myclass operator-=(myclass&, myclass);

friend myclass operator++(myclass&);
friend myclass operator--(myclass&);

friend myclass operator++(myclass&, int);
friend myclass operator--(myclass&, int);

friend myclass operator+(myclass,myclass);
friend myclass operator-(myclass,myclass);

friend myclass operator/(myclass, myclass);
friend myclass operator*(myclass, myclass);
friend myclass operator%(myclass, myclass);
};

myclass operator+=(myclass &ob1, myclass ob2 )
{
ob1.a+=ob2.a;
ob1.b+=ob2.b;

return ob1;
}

myclass operator-=(myclass &ob1, myclass ob2 )
{
ob1.a-=ob2.a;
ob1.b-=ob2.b;

return ob1;
}

myclass operator++(myclass &ob)
{
ob.a++;
ob.b++;

return ob;
}

myclass operator--(myclass &ob)
{
ob.a--;
ob.b--;

return ob;
}

myclass operator++(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a++;
ob.b++;

return temp;
}

myclass operator--(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a--;
ob.b--;

return temp;
}

myclass operator+(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a + ob2.a;
temp.b = ob1.b + ob2.b;

return temp;
}

myclass operator-(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a - ob2.a;
temp.b = ob1.b - ob2.b;

return temp;
}

myclass operator/(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a / ob2.a;
temp.b = ob1.b / ob2.b;

return temp;
}

myclass operator*(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a * ob2.a;
temp.b = ob1.b * ob2.b;

return temp;
}

myclass operator%(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a % ob2.a;
temp.b = ob1.b % ob2.b;

return temp;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a+=b;
a.show();

a++;
a.show();

a=a*a;
a.show();

a=a%b;
a.show();
}


Related Articles:


Overloading the Short-Hand Operators (+= and -=) using Friend Functions

In this article we’re going to overload the shorthand
addition (+=) and subtraction (-=) operators
using friend
functions.


As you can observe in the program below, the operator functions are taking
the first argument (operand) as a reference
(call by reference). This is due the fact that these operators need to alter
the data of the actual operand itself.


This is similar to the case of increment/decrement
operators
(click for detailed information).



// Overloading the shorthand
// += and -= operators using
// friend functions
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// declared as friend
friend myclass operator+=(myclass&, myclass);
friend myclass operator-=(myclass&, myclass);
};


myclass operator+=(myclass &ob1, myclass ob2 )
{
// data of the first operand
// are to be changed, so accepting
// it as a reference
ob1.a+=ob2.a;
ob1.b+=ob2.b;

return ob1;
}

myclass operator-=(myclass &ob1, myclass ob2 )
{
ob1.a-=ob2.a;
ob1.b-=ob2.b;

return ob1;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a+=b;
b+=a;

a.show();
b.show();
}


Related Articles:


Overloading Post-Fix Forms of ++ and -- Operators using Friend Functions

From the article Overloading
Post-Fix Forms of ++ and -- Operators
, we know that the postfix form
of the increment/decrement operator function takes two arguments, one is passed
implicitly
and the other as usual.


Its general form is:


  ret-type operator++(int);

As we know that when we overload operators as friends,
all the operands (arguments) are passed explicitly.


So, the general form for overloading postfix form of
increment/decrement operators
using friend functions should be (and
it really is) like this:


  ret-type operator++(class-name&, int);

Where the second int(eger) argument, as you know is a dummy variable and has
no use.


The following program illustrates this:



// Program to illustrate the overloading
// of increment / decrement operators
// as friends
// Overloads both prefix and postfix
// form
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// prefix form
friend myclass operator++(myclass&);
friend myclass operator--(myclass&);

// postfix form
friend myclass operator++(myclass&, int);
friend myclass operator--(myclass&, int);

};

// ---- PREFIX FORM ----
myclass operator++(myclass &ob)
{
ob.a++;
ob.b++;

return ob;
}

myclass operator--(myclass &ob)
{
ob.a--;
ob.b--;

return ob;
}
// ---- PREFIX FORM ENDS ----

// ---- POSTFIX FORM ----
myclass operator++(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a++;
ob.b++;

return temp;
}

myclass operator--(myclass &ob, int x)
{
myclass temp;
temp=ob;

ob.a--;
ob.b--;

return temp;
}
// ---- POSTFIX FORM ENDS ----

void main()
{
myclass a(10,20);
myclass b(100,200);

++a;
(b++).show();
b.show();

a.show();
b.show();

a=b++;

a.show();
b.show();
}


Related Articles:


Overloading Increment/Decrement Operators using Friend Functions

In the article Operator
Overloading using Friend Functions
, we saw how we can overload simple
operators using friend functions, in the other article Overloading
Increment/Decrement Operators
, we saw the method of overloading increment/decrement
operators as member functions. Combining both these, we’ll try to overload
the increment/decrement operators using friend
functions
, in this article.


As we know there are some differences in overloading operators as a friend.


Increment/decrement are the type of operators that need to change the operands
itself. In the case of operator overloading as member functions, ‘this’
pointer
was passed so any change done would result in the operand itself
getting changed. But in the case of friend functions, operands are passed explicitly
and that also as call by value, hence it is impossible to change the operand
that way.


Let’s take an example, suppose we have an object ‘ob’of a
class say 'myclass' which overloads the increment operator,


  ob++;

This statement would result in a call to the overloaded increment (++) operator
function, which could be something like the one below:


  myclass operator++()
{

a++;
b++;

return *this;
}

Supposing the data of the class we need to alter are a and b, the above statement
would increment the data of the object that generated the call, hence the desired
result is achieved.


Had the function been overloaded as a friend something like this:


  myclass operator++(myclass ob)
{
ob.a++;
ob.b++;

return ob;
}


Then the operand’s copy (not the actual object that generated the call)
would have been passed to the function and any change (a++ and b++) would only
have incremented the data of the copy of the object passed (call by value) and
the data of the operand would have remained unchanged.


To overcome this we need to accept the reference
of the object (call by reference) as the argument to overload the operators
as a friend.


The following program illustrates this method:



// Program to illustrate the overloading
// of increment / decrement operators
// as friends
// NOTE: Prefix form is overloaded here
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// accepting references
friend myclass operator++(myclass&);
friend myclass operator--(myclass&);

};

myclass operator++(myclass &ob)
{
ob.a++;
ob.b++;

return ob;
}

myclass operator--(myclass &ob)
{
ob.a--;
ob.b--;

return ob;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

++a;
++b;

a.show();
b.show();

a=--b;

a.show();
b.show();
}


Related Articles:


Operator Overloading using Friend Functions

In the article Introduction
to Operator Overloading in C++
, we discussed that there are two methods
by which operators can be overloaded, one using the member function and the
other by using friend
functions.


There are some differences between the two methods though, as well as there
are advantages for using friend functions to overload operators over member
functions.


In this article we’ll be overloading the simplest operators – and
+ using friend function. Previously we have seen that we need to accept only
one argument explicitly for binary operators and the other is passed implicitly
using the ‘this’
pointer.


From the article Friend
Functions of a Class
, we know that as friend functions are not members
of a class, they don’t have a ‘this’ pointer. So how the operands
are are passed in this case?


Simple, all the operands are passed explicitly to the friend operator functions.


There are other differences also but for this article (to overload + and –
operators) this is enough.


Here is the program:



// Using friend functions to
// overload addition and subtarction
// operators
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int x,int y){a=x;b=y;}
void show()
{
cout<<a<<endl<<b<<endl;
}

// these are friend operator functions
// NOTE: Both the operans will be be
// passed explicitely.
// operand to the left of the operator
// will be passed as the first argument
// and operand to the right as the second
// argument
friend myclass operator+(myclass,myclass);
friend myclass operator-(myclass,myclass);

};

myclass operator+(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a + ob2.a;
temp.b = ob1.b + ob2.b;

return temp;
}

myclass operator-(myclass ob1,myclass ob2)
{
myclass temp;

temp.a = ob1.a - ob2.a;
temp.b = ob1.b - ob2.b;

return temp;
}

void main()
{
myclass a(10,20);
myclass b(100,200);

a=a+b;

a.show();
}


Related Articles:


Class with all the Overloaded Arithmetic Operators

So far we have learnt to overload +, -, +=, -= etc. operators and we know what
is the basic theory behind operator overloading.


In this article we are going to design a program with a class that overloads
almost all the arithmetic operators (+, -, +=, -=, /, *, ++, --)


This is a program centric article, so we straightway have a look at the example
program.


Since nothing new has been introduced, I leave it up to you to understand everything
yourself.



// Example Program with a
// a class having almost
// all the arithmetic
// operators overloaded
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(){}
myclass(int,int);
void show();

myclass operator+(myclass);
myclass operator-(myclass);

// prefix
myclass operator++();
myclass operator--();

// postfix
myclass operator++(int);
myclass operator--(int);

myclass operator+=(myclass);
myclass operator-=(myclass);

myclass operator/(myclass);
myclass operator*(myclass);

};

myclass::myclass(int x,int y)
{
a=x;
b=y;
};

void myclass::show()
{
cout<<a<<endl<<b<<endl;
}

myclass myclass::operator+(myclass ob)
{
myclass temp;

temp.a=a + ob.a;
temp.b=b + ob.b;

return temp;
}

myclass myclass::operator-(myclass ob)
{
myclass temp;

temp.a=a - ob.a;
temp.b=b - ob.b;

return temp;
}

myclass myclass::operator++()
{
a++;
b++;

return *this;
}

myclass myclass::operator--()
{
a--;
b--;

return *this;
}

myclass myclass::operator++(int x)
{
myclass old;
old=*this;

a++;
b++;

return old;
}

myclass myclass::operator--(int x)
{
myclass old;
old=*this;

a--;
b--;

return old;
}

myclass myclass::operator+=(myclass ob)
{
a+=ob.a;
b+=ob.b;

return *this;
}

myclass myclass::operator-=(myclass ob)
{
a-=ob.a;
b-=ob.b;

return *this;
}

myclass myclass::operator/(myclass ob)
{
myclass temp;

temp.a=a / ob.a;
temp.b=b / ob.b;

return temp;
}

myclass myclass::operator*(myclass ob)
{
myclass temp;

temp.a=a * ob.a;
temp.b=b * ob.b;

return temp;
}

void main()
{
myclass ob1(10,20);
myclass ob2(100,200);

ob1+=ob2;

ob1.show();
ob2.show();

ob1=ob1/ob2;
ob1.show();

ob1=ob1*ob2;
ob1.show();

ob2.show();
}


Related Articles:


Overloading the Short-Hand Operators (+= and -=)

The short-hand addition (+=) and subtraction (-=) operators are very commonly
used and thus it would be nice if we overload them in classes. You would be
glad to know that there is nothing new or special that needs to be done to achieve
this, both the operators are overloaded as usual like other binary operators.


The short-hand operators combine the operation performed by two operators one
the addition or subtraction and the other the assignment. This is all it does
and this is all you need to know!


As nothing new has been introduced so we end the theory here and look at the
example:



// Program to illustrate the
// overloading of shorthand
// operators (+=, -=)
#include <iostream.h>

class myclass
{
int a;
int b;

public:
myclass(int,int);
void show();

myclass operator+=(myclass);
myclass operator-=(myclass);
};

myclass::myclass(int x,int y)
{
a=x;
b=y;
};

void myclass::show()
{
cout<<a<<endl<<b<<endl;
}

myclass myclass::operator+=(myclass ob)
{
a+=ob.a;
b+=ob.b;

// note this
return *this;
}

myclass myclass::operator-=(myclass ob)
{
a-=ob.a;
b-=ob.b;

// note this
return *this;
}

void main()
{
myclass ob1(10,20);
myclass ob2(100,200);

ob1+=ob2;

ob1.show();

// even this is possible
// because operator functions
// are retuning *this
ob2=ob1+=ob1;

ob2.show();
}


Related Articles:


Overloading Increment/Decrement Operators

In this article we are going to overload the increment (++) and decrement (--)
operators
by using operator
overloading
.


As increment (++) and decrement (--) are unary
operators
, therefore the operator functions that we need to define
won’t take any arguments.


These operators are overloaded as usual so further discussion is not required
and we straightaway look at the example program:



// overloading the increment
// and decrement operators
#include <iostream.h>

// class
class myclass
{
int a;

public:
myclass(int);
void show();

void operator ++();
void operator --();
};

myclass::myclass(int x)
{
a=x;
};

void myclass::show()
{
cout<<a<<endl;
}

void myclass::operator ++()
{
// increment a
a++;
}

void myclass::operator --()
{
// decrement a
a--;
}

// main
void main()
{
myclass ob(10);

ob.show();

++ob;
ob.show();

--ob;
ob.show();
}



The overloaded (++ and --) operators in the above program has some problems
however. As operator functions are not returning anything therefore a statement
like the one below is not legal.


  ob2 = ++ob;

Although pretty much used the above statement is not possible, of course unless
we return the object that generated the call from the overloaded operator function.
As in the line:


  ob2 = ++ob;

If we return the object ‘ob’ from the overloaded operator function
then the above statement would be perfectly legal.


To do this the ‘this’ pointer is used. The program with slight
modification is below:



// overloading the increment
// and decrement operators
// -- corrected version --
#include <iostream.h>

// class
class myclass
{
int a;

public:
myclass(int);
void show();

myclass operator ++();
myclass operator --();
};

myclass::myclass(int x)
{
a=x;
};

void myclass::show()
{
cout<<a<<endl;
}

myclass myclass::operator ++()
{
// increment a
a++;

// return the object
// that generated call
return *this;
}

myclass myclass::operator --()
{
// decrement a
a--;

// return the object
// that generated call
return *this;
}

// main
void main()
{
myclass ob(10);
myclass ob2(100);

ob.show();

++ob;
ob.show();

// now this is legal
// as the incremented
// value of ob may be
// assigned to other
// objects
ob2=++ob;
ob2.show();

--ob2;
ob2.show();
}


This is one of the situations when you can’t live without using the ‘this’
pointer!


NOTE: This way we can overload prefix form of the increment and decrement operators,
we'll be discussing postfix form in the coming articles.


Related Articles:


Check out this stream