티스토리 뷰

C++

Friend in C++

seoca 2018. 11. 22. 12:26



Friend

Friend allows access to members and methods declared private or protected by other classes or functions of other classes. It is used only in unavoidable situations such as operator overloading because it is in violation of encapsulation.



Example code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using namespace std;
 
class Apple; //forward declaration
 
class Banana{
private:
    int m_count = 3;
public:
    void print(Apple& a);  //declaration
};
 
class Apple {
private:
    int m_count = 6;
    friend void Banana::print(Apple& a); 
    //only Banana function is a friend.
};
 
void Banana::print(Apple& a) {  // definition
    cout << a.m_count << endl;
};
 
int main()
{
    Apple a;
    Banana b;
 
    b.print(a); //6
 
    return 0;
}
cs


'C++' 카테고리의 다른 글

Vector & List in C++  (0) 2018.11.22
Virtual Function in C++  (0) 2018.11.22
Templates (Function Template & Class Template) in C++  (0) 2018.11.10
Exception handling (Try Throw and Catch) in C++  (0) 2018.11.09
Inline function in C++  (0) 2018.11.09