Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
a class.
A situation may require two classes to share their data.
To handle this situation, friend function is used.
class abc Function declaration should
be preceded by friend
{ keyword.
... Function is defined outside as
... a normal C++ function.
public: Function definition will not
require the use of friend
friend void xyz(void); keyword or scope resolution
operator.
};
A function can be declared as
friend to any number of
classes.
A friend function , although
not a member function, has
full access to the private
members of the class.
Property:
To access the data members of a class in the
friend function, the object of the class is used
along with the dot operator.
#include<iostream> OUTPUT
using namespace std; Error
class X{ est.cpp: In function 'void disp()':
test.cpp:21:7: error: 'a' was not declared in this scope
int a; cout<<a<<"\n"<<b;
int b; ^
test.cpp:21:16: error: 'b' was not declared in this
scope
public: cout<<a<<"\n"<<b;
X(){ ^
test.cpp: In function 'int main()':
a=10; test.cpp:27:4: error: 'class X' has no member named
b=20; 'disp'
ob.disp();
} ^~~~
friend void disp();
};
void disp(){
cout<<a<<"\n"<<b;
}
int main(){
X ob;
ob.disp();
}
#include<iostream> OUTPUT
10
using namespace std; 20
class X{
int a;
int b;
public:
X(){
a=10;
b=20;
}
friend void disp(X ob2);
};
int main(){
X ob;
disp(ob);
}
Error
class Y{
int b;
public:
Y(){
b=20;
}
friend void disp(X ob1,Y ob2);
};
Output
15
class Y{
int b;
public:
Y(){
b=20;
}
friend void disp(X ob1,Y ob2);
};
It is not in the scope of the class to which it has been declared as friend.
Since it is not in scope of the class, it cannot be called using the object of that
class.
It can be invoked like a normal function without the help of any object.
Unlike member functions, it cannot access the member names directly and has
to use an object name and dot membership operator with each member name.
It can be declared either in the public or the private part of a class without
affecting its meaning.
20 10
10 20
20 10
20 10
10 10 10
-10 -10 -10
10 10 10
-10 -10 -10
};
void _3D::disp(){
cout<<x<<" "<<y<<" "<<z;
}
Output
10 10 10
-10 -10 -10
50 70 90
ob1.operator +(ob2);
10 20 30
40 50 60
50 70 90
50 70 90
Operator +(&ob1, &ob2);
10
30
11
11
int main()
{
test ob(10);
ob++;
ob.disp();
}
Output
10 10 10
-10 -10 -10