C++ friend functions

C++ allows a non-member function to access all private and protected members of a class. This is possible through the use of the keyword friend.

Example 1

Let us develop a program to implement the concept of friend function.

#include <iostream>
using namespace std;

class Price {
private:
int value;

public:
// constructor
Price() : value(10) { }

// friend function
friend int addTen(Price);
};

// friend function definition
int addTen(Price p) {
// accessing private members from friend function
p.value += 10;
return p.value;
}

int main() {
Price P;
cout << "Price: " << addTen(P);
return 0;
}

Output:

Price: 20

 

Example 2

Let us see another program to demonstrate the working of friend function.

#include <iostream>
using namespace std;

class B; // forward declaration

class A {
int x;
public:
void setData(int i) {
x = i;
}
friend void max(A, B); // friend function
};

class B {
int y;
public:
void setData(int i) {
y = i;
}
friend void max(A, B); // friend function
};

void max(A a, B b) {
if(a.x >= b.y)
cout << "Maximum: " << a.x << endl;
else
cout << "Maximum: " << b.y << endl;
}

int main() {
A a;
B b;
a.setData(30);
b.setData(20);
max(a, b);
return 0;
}

Output:

Maximum: 20

 

friend class

The concept of friend class is quite similar to that friend function. A friend class can access private and protected members of other class in which it is declared as friend. However, the reverse is not true. See the following example.

Example 3

Let us develop a program to implement the concept of friend function.

#include <iostream>
using namespace std;

// forward declaration
class ClassB;

class ClassA {
private:
int numA;

// friend class declaration
friend class ClassB;

public:
// constructor to initialize numA to 13
ClassA() : numA(13) { }
};

class ClassB {
private:
int numB;

public:
// constructor to initialize numB to 12
ClassB() : numB(12) { }

// member function to add numA of ClassA and numB of ClassB
int add() {
ClassA objectA;
return objectA.numA + numB;
}
};

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

Output:

Sum: 25