Search code examples
c++friend

Why am I getting the error 'cannot access private member declared in class' even though I have declared friend class


Consider the following code:

#include <iostream>

template<typename T>
class A
{
    private:
        T value;

    public:
        A(T v){ value = v;}

        friend class A<int>;
};

template<typename T>
class B
{
    public:
        T method(A<T> a){ return a.value; }  // problem here, but why?
};

int main()
{
    A<int> a(2);
    B<int> b;

    std::cout << b.method(a) << std::endl;
}

Why do I still get the error: "'A::value': cannot access private member declared in class 'A'" even though I have declared A as a friend class for the template type int?

Edit Note that moving the friend class line inside B also does not work:

template<typename T>
class A
{
    private:
        T value;

    public:
        A(T v){ value = v; }
};

template<typename T>
class B
{
    public:
    T method(A<T> a){ return a.value; }

    friend class A<int>;
};

Solution

  • template<typename T>
    class B;
    
    template<typename T>
    class A
    {
        private:
            T value;
        public:
            A(T v){ value = v;}
            friend class B<int>;
    };
    
    template<typename T>
    class B
    {
        public:
            T method(A<T> a){ return a.value; }
    };
    

    The class A should have class B as a friend , if you want B to use A's private attributes.