0% found this document useful (0 votes)
10 views

Friend and Static Function

The document discusses the use of friend functions in C++ by providing examples of how friend functions can access private members of a class and compare objects of different classes. It also demonstrates static data members and static member functions through an example that tracks the count of objects created.

Uploaded by

T. Yeasmin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Friend and Static Function

The document discusses the use of friend functions in C++ by providing examples of how friend functions can access private members of a class and compare objects of different classes. It also demonstrates static data members and static member functions through an example that tracks the count of objects created.

Uploaded by

T. Yeasmin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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