Search code examples
c++friendfriend-class

C++ access member-function from friend class


Is there a way to access member-function from the friend class?

// foo.h

template<typename T>
class A
{
    bool operator()(Item* item)
    {
        ObjectClass c = get_class_from_item(item); // compiler error
        ...
    }
};

class B
{
    ...
    template<typename T> friend class A;
    ...
    ObjectClass get_class_from_item(Item* item);
};

If it matters I use gcc 4.5.2


Solution

  • If get_class_from_item is supposed to be some kind of Factory function, which it seems to be, you need to make it static. You get the error because your compiler is looking for a function named get_class_from_item in class A. It will never see the function in B because it is not in the scope and you don't have an instance of class B. Here is some more explanation on Wikipedia: http://en.wikipedia.org/wiki/Factory_function.

    This should do it:

    class A
    {
        bool operator()(Item * item)
        {
            ObjectClass c = B::get_class_from_item(item);
            ...
        }
    };
    
    class B
    {
        static ObjectClass get_class_from_item(Item* item);
    };
    

    Also, is there a reason that A needs to be a friend class of B? Or did you just do that trying to get get_class_from_itemto work? Does A need to be able to access some private elements of B? Think carefully about this, most of the time there are better ways of obtaining what you want instead of throwing away all encapsulation by using friend.

    [Edit] Removed lines from code example to strip it to the bare minimum.