Skip to content

Commit bd0177e

Browse files
committed
friend function in cpp
1 parent cc5c6e4 commit bd0177e

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

FriendFunction.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//friend function
2+
#include<iostream>
3+
#include<string>
4+
5+
using namespace std;
6+
7+
void display(); //function prototype
8+
9+
class Human {
10+
private: //private attr of the class
11+
int age;
12+
int salary;
13+
string name;
14+
public:
15+
Human(int iage,int isal,string iname) {
16+
age=iage;
17+
salary=isal;
18+
name=iname;
19+
}
20+
void tell(){
21+
cout<<age<<salary<<endl<<name<<endl;
22+
}
23+
24+
friend void display(Human *anish); //friend function of class Human which can access the private and protected attr and methods of the class Human
25+
//friend function takes class object as argument
26+
27+
};
28+
29+
//friend function defination
30+
void display(Human *anish) {
31+
32+
cout<<"name: " <<anish->name<<","<<"salary : "<<anish->salary<<", "<<"age:"<<anish->age<<endl;
33+
}
34+
35+
36+
int main() {
37+
38+
Human *obj=new Human(20,2004444,"Anish Singh Walia");
39+
display(obj);
40+
41+
return 0;
42+
43+
}

StaticClass.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ int main () {
3737

3838
Human :: totalHuman();
3939
//can access static variables and methods without using an object of class.
40-
cout<<Human :: scount;
40+
cout<< Human :: scount;
4141

4242

4343
return 0;

0 commit comments

Comments
 (0)