Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Friend Function:

/* C++ program to show use of friend function. */


#include<iostream>
using namespace std;
class Sample
{
int a;
int b;
public:
void setValue(){ a = 20; b = 30}
friend float mean(Sample s);

};

float mean(Sample s){


float m;
m = (s.a + s.b)/2;
return m;
}

int main()
{
Sample x;
x.setValue();
cout << "Mean = "<< mean(x) << endl;
return 0;
}
Friend Function (example 2):
/* Use of friend function to compare object of different class. */

#include<iostream>
using namespace std;

class XYZ;
class ABC
{
int a;
public:
void setValue( int i){ a = i; }
friend void maximum(XYZ, ABC);
};

class XYZ
{
int a;
public:
void setValue( int i){ a = i; }
friend void maximum(XYZ, ABC);
};

void maximum(XYZ p, ABC q){


if(p.a > q.a){
cout <<"MAX is XYZ = " <<p.a<<endl;
}else{

cout <<"MAX is ABC = " <<q.a<<endl;


}
}

int main()
{
ABC a1;
a1.setValue(25);

XYZ x1;
x1.setValue(28);

maximum(x1,a1);

return 0;
}
Static members
/* C++ program to illustrate use of Static data member and static
member function. */

#include<iostream>
using namespace std;

class Item
{
static int cnt;
int code;
public:
void get_data(int x){
code = x;
cnt++;
}
static void get_count(){
cout<<"Count = "<<cnt<<endl;
}
void get_code(){
cout<<"Code = "<<code<<endl;
}
};

int Item::cnt;

int main()
{
Item a,b,c;
a.get_data(10);
b.get_data(20);
c.get_data(30);

a.get_code();
b.get_code();
c.get_code();

Item::get_count();

return 0;
}

You might also like