Functions
Functions
{ if(x>y) return x;
else return y;
}
Since the return type of max() is int&, the function returns
SYNTAX:
inline return-type function-name(parameters)
{ // function code }
FRIEND FUNCTION
A friend function is an outside function that can be
made friend to a class.
The function declaration should be preceded by the
keyword ‘friend’.
The function definition does not use the keyword
friend or the scope resolution operator.
The friend function can access the private members of
the class.
PROPERTIES OF FRIEND FUNCTION
It is not in the scope of the class to which it has been declared
as friend.
It cannot be called using the object of that class.
It can be invoked like a normal function.
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.
Usually, it has the objects as arguments.
FRIEND FUNCTION
#include<iostream> int main()
using namespace std; {
class sample sample x;
{ int a,b; //private // x.setvalue();
public: cout<<“mean
value=“<<mean(x); //call
sample() {a=25;b=40;}
return 0;
// void setvalue() {a=25; b=40;}
}
friend float mean(sample s);
//declaration
};
float mean(sample s) //definition
{
return float (s.a+s.b)/2.0;
}
FRIEND CLASS
#include<iostream> friend void max(XYZ,ABC);
using namespace std; };
class ABC; //forward declaration void max(XYZ m, ABC n)
class XYZ {
{ if(m.x>=n.a)
int x; cout<<m.x;
public: else
void setvalue(int i) cout<<n.a;
{ x=i;} }
friend void max(XYZ,ABC); int main()
}; {
class ABC ABC abc;
{ abc.setvalue(10);
int a; XYZ xyz;
public: xyz.setvalue(20);
void setvalue(int i) max(xyz,abc);
{ a=i;} return 0;
}
STATIC MEMBER FUNCTIONS
It can have access to only other static members (functions or
variables) declared in the same class.
It can be called using the class name (instead of its objects) as
follows:
class-name :: function-name;
STATIC MEMBER FUNCTIONS
#include<iostream> int test :: count;
using namespace std; int main()
class test {
{ test t1,t2;
static int count; t1.setcode();//count=1, code=1
int code=0; t2.setcode();//count=2,code=1
public: test:: showcount();//2
void setcode() test t3;
{ t3.setcode();//count=3,code=1
code=++count; test:: showcount();//3
} return 0;
static void showcount() }
{
cout<<“count:”<<count<<“\n”;
// cout<<code; //error, code is not
//static
}
};
RECURSION
A function that calls itself is known as a recursive
function. And, this technique is known as recursion.
FACTORIAL OF A NUMBER USING RECURSION