Static Data Member & Member Function, Array of Objects
Static Data Member & Member Function, Array of Objects
Array of Objects
KALINGA INSTITUTE OF INDUSTRIAL
TECHNOLOGY
Syntax:
function_name(object_name);
Object as Function arguments
10
Object as Function arguments-Pass by Value
11
Object as Function arguments-Pass by Address
12
Example: Object as Function arguments
13
C++ Friend function
14
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:
15
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:
16
#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:
17
Syntax:
class X
{
....
int fun1();
....
};
class Y
{
....
friend int X::fun1();
....
};
Member function one class can be friend function
of another class:
18
#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)
{ };
data=value; void add (XYZ obj1, ABC obj2 )
{
}
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); }
19