Friend keyword in C++

Friend functions in classes is an advance topic. If you do not understand the fundamentals of Object orientated programming in C++, read Understanding basic object orientated programming and implementing a class step by step.  

The friend keyword in C++ can simply access the private and protected members of the class, when it is declared as a friend. When granting access to a class, you must specify that access is granted for a class using the friend keyword. The difference between using inheritance and the friend keyword in object orientated is the following:

  • Using friendship, if you have two classes named A and B, it allows access to the private/protected members data and functions of class C
  • With inheritance, Class C and touch the public and protected members of Class A and B
  • Friendship are not inherited 
</pre>
<pre>// Friend class example code
#include <iostream>
using namespace std;

class Cylinder;
class Cube;

enum colors {red, green, yellow};

class Cube
{
// Private member
colors color;
public:
Cube(colors c) { color = c; }
friend bool sameColor(Cube x, Cylinder y);
};

class Cylinder
{
colors color; // Private member
public:
Cylinder(colors c) {color = c; }
friend bool sameColor(Cube x, Cylinder y);
};

bool sameColor(Cube x, Cylinder y)
{

if(x.color == y.color) return true;
else return false;
}
void main()
{
Cube cube1(red);
Cube cube2(green);
Cylinder cyl(green);

if(sameColor(cube1, cyl))
cout << "cube1 and cyl are the same color\n";
else
cout << "cube1 and cyl are different color\n";
if(sameColor(cube2, cyl))
cout << "cube2 and cyl are the same color\n";
else
cout << "cube2 and cyl are different color\n";
}</pre>
<pre>
Share this post