+ Reply to Thread
Results 1 to 2 of 2

Thread: Example where I have to use 'friend' function for class not member function.

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    24

    Example where I have to use 'friend' function for class not member function.

    Is there any example that I cannot create a member function for a class and I have to have use friend function rather?

    Is there any real use of 'friend' keyword rather than just accessing private data/method member of a class?

    Give me some example.

  2. #2
    Below example shows how friend function can be used in operator overloading where sometimes class member function is not enough:

    Code:
    class CIncrement
    {
    	int m_nValue ;
    public:
    	CIncrement()
    	{
    		m_nValue = 0 ;
    	}
    
    	CIncrement(int nValue)
    	{
    		m_nValue = nValue ;
    	}
    
    	friend CIncrement operator +(int n, CIncrement& obj1)
    	{
    		CIncrement objTemp ;
    		objTemp.m_nValue = obj1.m_nValue + n ;
    
    		return objTemp ;
    	}
    
    	CIncrement operator +(int n)
    	{
    		CIncrement objTemp ;
    
    		objTemp.m_nValue = m_nValue + n ;
    
    		return objTemp ;
    	}
    } ;
    
    void UseoperatorOverloading()
    {
    	CIncrement objIncrement1(10) ;
    
    	CIncrement objIncrement2 = 10 + objIncrement1 ; //this requires 'friend' function!
    
    	CIncrement objIncrement3 = objIncrement1 + 10 ;
    }
    Hope this helps.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts