Kalinga Institute of Industrial Technology School of Computer Engineering
Kalinga Institute of Industrial Technology School of Computer Engineering
Syntax:
function_name(object_name);
Object as Function arguments
9
A copy of the entire object is passed to the function.
Only the address of the object is transfered to the function.
Syntax:
function_name(object_name);
C++ Friend function
10
If a function is defined as a friend function in C++, then the protected and
private data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend
function.
For accessing the data, the declaration of a friend function should be done
inside the body of a class starting with the keyword friend.
Declaration of friend function in C++:
class class_name
{
friend data_type function_name(argument/s); // syntax of friend
function.
};
Characteristics of a Friend function:
11
The function is not in the scope of the class to which it has been declared as a
friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and
dot membership operator with the member name.
It can be declared either in the private or the public part.
The function defination does not use either the keyword friend or the scope
operator :: .
A function can be declared as a friend in any number of classes.
A friend function, although not a member function , has full rights to the
private members of the class.
Characteristics of a Friend function:
12
#include <iostream>
float mean( sample s)
#include <string>
{
using namespace std;
return float(s.a+s.b)/2.0;
class Sample
}
{ int main()
int a,b; {
sample x;
public: x.setvalue();
void setvalue() cout<< “Mean value=”<<mean(x);
{ return 0
a=25,b=40; }
}
friend float mean(sample s)
};
Member function one class can be friend function
of another class:
13
Syntax:
class X
{
....
int fun1();
....
};
class Y
{
....
friend int X::fun1();
....
};
Member function one class can be friend function
of another class:
14
#include <iostream>
using namespace std; class ABC{
int data;
class ABC;
public:
class XYZ
void setvalue(int value)
{ {
int data; data=value;
public: }
void setvalue(int value) friend void add(XYZ,ABC)
{ };
void add (XYZ obj1, ABC obj2 )
data=value;
{
}
cout<<”sum=”<<obj1.data+obj2.data;
friend void add(XYZ,ABC)
}
}; int main(){
XYZ X; ABC A;
X.setvalue(5);
A.setvalue(10); add(X,A); }
15