+ Reply to Thread
Results 1 to 2 of 2

Thread: What is the 'friend' keyword in C++?

  1. #1

    What is the 'friend' keyword in C++?

    Hi All,

    What is the 'friend' keyword in C++?

    Regards.

  2. #2
    Hi,

    'friend' keyword is used to access private and protected member of the class that is outside of the class.

    Only 'friend' and 'derived' class can access 'protected' member of the class.

    Only 'friend' of the class can access 'private' member of the class.

    That is why it is called 'friend'.

    Below example shows you how a friend 'function' can access a private member of the class.

    Code:
    class CStudent
    {
    	friend void FriendFunction(CStudent& objStudent) ;
    
    private:
    	int m_nPrivate ;
    
    protected:
    	int m_nProtected ;
    
    public:
    	int m_nPublic ;
    
    	CStudent()
    	{
    		m_nPrivate		= 0 ;
    		m_nProtected	= 1 ;
    		m_nPublic		= 2 ;
    	}
    
    	int GetPrivate()
    	{
    		return m_nPrivate ;
    	}
    	
    	int GetProtected()
    	{
    		return m_nProtected ;
    	}
    } ;
    
    void FriendFunction(CStudent& objStudent)
    {
    	//It works as FriendFunction is friend function of CStudent class
    	 int nPrivate	= objStudent.m_nPrivate ;
    
    	 //friend function can change value too!
    	 objStudent.m_nPrivate = 10 ;
    	 
    	 
    	 //It works as FriendFunction is friend function of CStudent class
    	 int nProtected = objStudent.m_nProtected ;
    
    	 //friend function can change value too!
    	 objStudent.m_nProtected = 20 ; 
    
    	 int nPublic = objStudent.m_nPublic ;
    }
    
    void UseFriend()
    {
    	 CStudent objStudent ;
    
    	 FriendFunction(objStudent) ;
    }
    Thanks.

+ 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