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);
}
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
Post a Comment