maverik
maverik

Reputation: 5586

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

Upvotes: 0

Views: 599

Answers (2)

Naveen
Naveen

Reputation: 73443

No, since get_class_from_item is a member function you need an instance of class B to call it.

Upvotes: 2

AVH
AVH

Reputation: 11516

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.

Upvotes: 3

Related Questions