C++ program to demonstrate the example of friend function with class.

Program Code:
#include <iostream>
using namespace std;
class Num
{

private:
int a;
public:
void getdata(int x);
//declaration of friend function
friend void putdata(Num N);
}; 
//class member function definitions outside the class declaration with Scope Resolution Operator (::)
void Num :: getdata(int x)
{
a=x;
//friend function definition, outside the class declaration without Scope Resolution Operator (::)
void putdata(Num N)
{
cout << "Value of a (private data member of class Num) : " << N.a; 
int main()
{
//Object declaration of class Num
Num obj; 
// call to member function of class with class object and dot (.) operator
obj.getdata(10);
// call to friend function of class without class object and dot (.) operator

putdata(obj); 
return 0;
}

The program output is tested on www.jdoodle.com
Output:
Value of a (private data member of class Num) : 10


Thanks
Mukesh Rajput

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: