The document provides examples of using friend functions in C++.
In the first example, a friend function "add()" is declared and defined to access private members of class "Sum" to add two numbers. The second example demonstrates how a friend function "fun()" can access private members of two different classes "A" and "B". The third example shows how a static member function and static data member can be accessed using the class name and scope resolution operator.
6. 6
Example
class Sum
{
private:
int a, b;
public:
void get_num()
{
cout<<Enter any two numbers:n;
cin>>a>>b;
}
friend int add(); //Friend function
Declaration
};
int add() // Friend function Defination
{
Sum s;
int temp;
s.get_num();
temp=s.a+s.b; // accessing private data
return temp;
}
int main()
{
int result;
result=add();
cout<<Sum=<<result<<endl;
}
Output
Enter any two numbers:
7
3
Sum= 10
13. 13
Example
class example
{
private:
static int sum; //Static data
int x;
public:
example() //Constructor of the class
{
sum=sum+1;
x=sum;
}
~example() //Destructor of the class
{
sum=sum-1;
}
static void exforsys()
//Static function exforsys( ) defined with keyword
static
{
cout << "nResult is: " << sum;
}
void number() //Normal member
function number( )
{
cout << "nNumber is: " << x;
}
};
int example::sum=0;
void main()
{
example e1;
example::exforsys();
//Static function exforsys() accessed
using class name example and the scope
resolution operator ::
example e2,e3,e4;
example::exforsys();
e1.number();
14. 14
//Normal member function accessed using
object e1 and the dot member access
operator.
e2.number();
e3.number();
e4.number();
}
OUTPUT:
Result is:1
Result is:4
Number is:1
Number is:2
Number is:3
Number is:4
36. Example
class vehicle
//base class of C++ virtual function
{
public:
virtual void make ( ) // C++ virtual
function
{ cout<<" member function of base class
vehicle accessed" <<endl;}
};
class fourwheeler : public vehicle
{
public:
void make ( )
{
cout <<" virtual member function of derived
class fourwheeler accessed"<< endl;}
};
int main ( )
{
vehicle *a, *b;
a = new vehicle ( );
a-> make ( );
b = new fourwheeler ( );
b-> make ( );
return 0;}
Output:
Member function of base class
vehicle accessed
virtual member function of derived
class fourwheeler accessed.
36