Site icon T4Tutorials.com

C++ example with and without friend function

C++ example with a program with friend function
C++ example with a program with friend function

C++ Program without friend function

#include <iostream>
using namespace std;
class one {
private:
int n1=1;
public:
int add(one object1)
{
return (object1.n1 + 1);
}
};

int main()
{
one object1;
cout<<"Sum: "<< object1.add(object1);
return 0;
}

C++ Program with friend function

#include <iostream>
using namespace std;
class one {
private:
int n1=1;
public:
friend int add(one);
};

int main()
{
one object1;
cout<<"Sum: "<< add(object1);
return 0;
}
int add(one object1)
{
return (object1.n1 + 1);
}

How Friend function Can access private, protected, and public members of a class 

 

 

Exit mobile version