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
Post A Comment:
0 comments: