What is friend function?

Special function which can access private members of an instance which is generally not allowed.

The function must be marked as friend using friend keyword inside the class.

Example

#include<iostream>
#include<math.h>
using namespace std;
class Number
{
private:
int num;
public:
Number(int num)
{
this->num=num;
}
void cube()
{
cout <<"Cube of "<< num << " is "<< num*num*num<<endl;
}
friend void cubeRoot(Number x);
};

void cubeRoot(Number x)
{
cout << "Cube root of "<< x.num << " is " << pow(x.num,1.0/3) << endl;
}
main()
{
Number x(6);
x.cube();
cubeRoot(x);
}

Comments

Popular posts from this blog

What is template?

Can we access private members of an instance?

What are wrapper classes in Java?