Showing posts with label friend function. Show all posts
Showing posts with label friend function. Show all posts

Sunday, April 6, 2014

C++ Program to swap two integers using friend function

C++ Program to swap two integers using friend function

In object-oriented programming, a friend function that is a "friend" of a given class is allowed access to private and protected data in that class that it would not normally be able to as if the data was public. Normally, a function that is defined outside of a class cannot access such information. Declaring a function a friend of a class allows this, in languages where the concept is supported.
                                                                                         wiki

#include<iostream.h>
class b;
class a
{
int x1;
public:
void reada()
{
cout<<"Enter x1 value\n";
cin>>x1;
}
friend void swap (a &,b &);
};
class b
{
int x2;
public:
void readb()
{
cout<<"Enter an x2 value\n";
cin>>x2;
}
friend void swap (a &,b &);
};
void swap (a &o1, b &o2)
{
int t;
cout<<"Before swapping\nx1="<<o1.x1<<"\n"<<"x2="<<o2.x2<<"\n";
t=o1.x1;
o1.x1=o2.x2;
o2.x2=t;
cout<<"After swapping\nx1="<<o1.x1<<"\n"<<"x2="<<o2.x2<<"\n";
}
void main()
{
clrscr();
a a;
a.reada();
b b;
b.readb();
swap(a,b);
}

Tuesday, April 1, 2014

C++ Program to demonstrate operator overloading

C++ Program to demonstrate operator overloading function (Unary Operator) Using friend function
#include<iostream>
class A
{
int x,y;
public:
void input ()
{
cout<<"Enter X and Y values\n";
cin>>x>>y;
}
void disp()
{
cout<<"x is "<<x<<endl<<"y= "<<y<<endl;
}
friend void operator --(A &o);
friend void operator ++(A &o);
};
void operator --(A &o)
{
o.x=--o.x;
o.y=--o.y;
}
void operator ++(A &o)
{
o.x++;
o.x=o.x;
o.y++;
o.y=o.y;
}
int main()
{
A a;
a.input();
a.disp();
cout<<"After decrimenting\n";
//accessing unary minus operator
--a;//calling operator -()
a.disp();
++a;
cout<<"After incrimenting\n";
a.disp();
return 0;
}