A friend function in C++ is a function declared with the keyword friend within a class, allowing it access to private and protected data members of that class.
#include <iostream.h>
#include <conio.h>
class MyClass {
private:
int data;
public:
MyClass() { data = 0; }
friend void showData(MyClass& obj); // Friend function declaration
};
void showData(MyClass& obj) {
cout << "Data: " << obj.data << endl;
}
void main() {
clrscr();
MyClass obj;
showData(obj);
getch();
}
A friend function can access private data members of a class even though it is not a member of that class.
#include <iostream.h>
#include <conio.h>
class Sample {
private:
int value;
public:
Sample(int v) { value = v; }
friend void displayValue(Sample& s); // Friend function
};
void displayValue(Sample& s) {
cout << "Value: " << s.value << endl;
}
void main() {
clrscr();
Sample s(42);
displayValue(s);
getch();
}
Friend functions can also be defined as inline functions in Turbo C++ to optimize performance.
#include <iostream.h>
#include <conio.h>
class Test {
private:
int num;
public:
Test(int n) { num = n; }
friend inline void printNum(Test& t) {
cout << "Number: " << t.num << endl;
}
};
void main() {
clrscr();
Test t(100);
printNum(t);
getch();
}
One class can be a friend of another, allowing it access to its private and protected members.
#include <iostream.h>
#include <conio.h>
class A {
private:
int x;
public:
A(int val) { x = val; }
friend class B; // Granting friendship to class B
};
class B {
public:
void showX(A& a) {
cout << "X: " << a.x << endl;
}
};
void main() {
clrscr();
A a(20);
B b;
b.showX(a);
getch();
}
A single function can be a friend of multiple classes, allowing it to access private data from different classes.
#include <iostream.h>
#include <conio.h>
class Class1;
class Class2;
class FriendFunction {
public:
void showData(Class1& c1, Class2& c2);
};
class Class1 {
private:
int data1;
public:
Class1(int val) { data1 = val; }
friend void FriendFunction::showData(Class1&, Class2&);
};
class Class2 {
private:
int data2;
public:
Class2(int val) { data2 = val; }
friend void FriendFunction::showData(Class1&, Class2&);
};
void FriendFunction::showData(Class1& c1, Class2& c2) {
cout << "Class1 data: " << c1.data1 << ", Class2 data: " << c2.data2 << endl;
}
void main() {
clrscr();
Class1 c1(10);
Class2 c2(20);
FriendFunction f;
f.showData(c1, c2);
getch();
}