-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12_friendFunction.cpp
More file actions
46 lines (36 loc) · 992 Bytes
/
12_friendFunction.cpp
File metadata and controls
46 lines (36 loc) · 992 Bytes
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* Friend can be function or classes
* Mostly used to display some inf about classes (<<)
*/
#include <iostream>
using namespace std;
class rectangle{
public:
rectangle( int xa, int xb ) : a( xa ), b( xb ){}
/*
* Frined function is declared in public space
* Using frined keyword at the begining
* Friend function, although declared outside this class,
* can access private attributes just like function of this class
* -> it is declared outside this class
* ->it is not a member of this class, can only access its attributes
*/
friend void calcArea( rectangle &x );
int getArea() { return this->area; };
private:
int a;
int b;
int area;
};
void calcArea ( rectangle &x ){
cout << x.a * x.b << endl;
//passed object has to be reference
//because next line writes to obj attribute
x.area = x.a * x.b;
};
int main(){
rectangle r1(10, 5);
calcArea( r1 );
cout << r1.getArea() << endl;
return 0;
}