Tuesday, October 2, 2012

program to swap the values of 2 different object

c++ program code for swapping the values of different object (uses freind function concept)

c++ program code for swaping the values of different object

#include<iostream.h>
#include<conio.h>
class sample
{
int x;
public:
void read();
friend void display(sample,sample);
friend void swap(sample,sample);
};
void sample::read()
{
cout<<"Enter the value\n";
cin>>x;
}
void display(sample s1,sample s2)
{
cout<<"Before swaping\n";
cout<<"s1  "<<s1.x;
cout<<"\ns2  " <<s2.x;
}

void swap( sample s1,sample s2)
{
int t;
t=s1.x;
s1.x=s2.x;
s2.x=t;
cout<<"\nAfter swaping\n";
cout<<"s1  "<<s1.x;
cout<<"\ns2  " <<s2.x;
}
void main()
{
clrscr();
sample s1,s2;
s1.read();
s2.read();

display(s1,s2);
swap(s1,s2);
getch();
}

 what is an object?

A region of storage with associated semantics.
After the declaration int i; we say that "i is an object of type int." In OO/C++, "object" usually means "an instance of a class." Thus a class defines the behavior of possibly many objects (instances).

No comments:

Post a Comment