Skip to content

Commit 63b8f95

Browse files
Added the code for Friend Class in C++
1 parent 5a1620c commit 63b8f95

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// C++ program to demonstrate Friend Class
2+
3+
// Friend Class - A friend class can access the private and protected members of the class in which
4+
// it is declared as a friend.
5+
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
9+
// class with Friend class
10+
class Person{
11+
private:
12+
string name;
13+
int age;
14+
public:
15+
Person(string iname,int iage){
16+
name=iname;
17+
age=iage;
18+
}
19+
// class Introduce is a friend of class Person
20+
friend class Introduce;
21+
};
22+
23+
// Friend class
24+
class Introduce{
25+
public:
26+
void display(Person& x){
27+
cout<<"Name : "<<x.name<<endl;
28+
cout<<"Age : "<<x.age<<endl;
29+
}
30+
};
31+
32+
int main(){
33+
// Creating an object of class Person
34+
Person p("abc",10);
35+
36+
// Creating an object of class Introduce
37+
Introduce i;
38+
39+
// Accessing private members of class Person through class Introduce
40+
i.display(p);
41+
return 0;
42+
}

0 commit comments

Comments
 (0)