+ Reply to Thread
Results 1 to 2 of 2

Thread: Can friendship be inherited in C++?

  1. #1

    Can friendship be inherited in C++?

    I have a class A and it has friend class F.

    If I derive a class B from class A then F is friend of B or not?

    Can friendship be inherited in C++?

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    No, friendship cannot be inherited.

    Example:

    Code:
    class F ;
    class A
    {
    private:
    	int m_nA ;
    	friend class F ;
    public:	
    	A()
    	{
    		
    	}
    
    	~A()
    	{
    	}
    } ;
    
    
    class B : public A
    {
    private:
    	int m_nB ;
    public:	
    	B() : A()
    	{
    		
    	}
    
    	~B()
    	{
    		
    	}
    } ;
    
    class F
    {
    public:
    	F() {}
    	void UseA(const A& objA)
    	{
    		int nA = objA.m_nA ;
    	}
    
    	//error C2248: 'm_nB' : cannot access private member declared in class 'B'
    	/*
    	void UseB(const B& objB)
    	{
    		int nB = objB.m_nB ;
    	}
    	*/
    } ;

+ 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