Thursday, 19 March 2009

Example of friend class and friend function

The following example shows a simple friend class and friend function example:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows a basic example of friend class and function
#include<iostream>

using namespace
std;

class
A {
public
:
int
square(int num)
{
return num*num;}
protected
:
int
reduced_square(int num)
{
return (num-1)*(num-1);}
private
:
int
cube(int num)
{
return num*num*num;}
friend class
B;
};


//Class B friend of class A
class B {
public
:
int
b_square(int num)
{

A a;
return
a.square(num);
}

int
b_reduced_square(int num)
{

A a;
return
a.reduced_square(num);
}

int
b_cube(int num)
{

A a;
return
a.cube(num);
}

private
:
int
b_priv;
int
b_default_cube()
{

return
b_cube(b_priv);
}

friend
int C(int c);
};


//function C friend of Class B
int C(int c)
{

B b;
b.b_priv = c;
//A a;
//return a.cube(b.b_priv); - Not possible as C is not friend of A
return b.b_default_cube();
}



int
main()
{

cout<<"\nExample of Friend Class and Function"<<endl;
A a;
cout<<"\nA: Square of 3 = "<<a.square(3)<<endl;
//The following is not possible
//cout<<"Reduced Square of 3 = "<<a.reduced_square(3)<<endl;
//cout<<"Cube of 3 = "<<a.cube(3)<<endl;

B b;
cout<<"\nB: Square of 4 = "<<b.b_square(4)<<endl;
cout<<"B: Reduced Square of 4 = "<<b.b_reduced_square(4)<<endl;
cout<<"B: Cube of 4 = "<<b.b_cube(4)<<endl;

cout<<"\nC: Cube of 5 = "<<C(5)<<endl;

return
0;
}



The output is as follows:

1 comment:

  1. very nice exmaple to understand the friend function

    ReplyDelete