Search code examples
c++visual-c++intellisensefriendaccess-control

Friend member function cannot access private member


I have the following:

class B;

class A
{
public:
    int AFunc(const B& b);
};

class B
{
private:
    int i_;
    friend int A::AFunc(const B&);
};

int A::AFunc(const B& b) { return b.i_; }

For the definition of AFunc I get that member B::i_ is inaccessible. What am I doing wrong?

Compiler: MSVC 2013.

Update: Changed AFunc to public and the code now compiles. However I still get an IntelliSense error. Is this a problem with IntelliSense?


Solution

  • The problem is that you are were declaring another class's private function as a friend! B should normally have no knowledge of A's private member functions. G++ 4.9 has the following to say:

    test.cpp:6:9: error: 'int A::AFunc(const B&)' is private
         int AFunc(const B& b);
             ^
    test.cpp:13:33: error: within this context
         friend int A::AFunc(const B&);
                                     ^
    

    To solve this, simply declare B as a friend of A:

    class A
    {
        friend class B;
    private:
        int AFunc(const B& b);
    };
    

    You might be interested in Microsoft's example.