Friend Functions and Classes
Breaking encapsulation when needed
Interview Relevant: Access control
Friend Functions and Classes
Friends can access private members of a class.
Code Examples
Using friend for controlled access violation.
cpp
1class Box {
2 double width;
3
4public:
5 Box(double w) : width(w) {}
6
7 // Friend function declaration
8 friend void printWidth(const Box& b);
9
10 // Friend class
11 friend class BoxPrinter;
12
13 // Friend operator
14 friend ostream& operator<<(ostream& os, const Box& b);
15};
16
17// Friend function definition
18void printWidth(const Box& b) {
19 cout << b.width << endl; // Access private member
20}
21
22// Friend class
23class BoxPrinter {
24public:
25 void print(const Box& b) {
26 cout << "Width: " << b.width << endl;
27 }
28};
29
30// Friend operator
31ostream& operator<<(ostream& os, const Box& b) {
32 os << "Box(" << b.width << ")";
33 return os;
34}
35
36Box b(5.0);
37printWidth(b); // 5
38cout << b << endl; // Box(5)