Friend protected method in c++

greywolf82 picture greywolf82 · Aug 17, 2014 · Viewed 7.5k times · Source

I've got a class Foo that must be accessed "directly" in other class Bar. I'd like to build a little framework declaring the method of Bar (which is the friend method of Foo) protected. In this way I could build several classes children of Bar.

Gcc complains about that and it works only if the method is public.

How can I do? Example of my code:

class Foo;
class Bar {
    protected:
        float* internal(Foo& f);
};
class Foo {
    private:
        //some data
    public:
        //some methods
        friend float* Bar::internal(Foo& f);
};

Gcc message:

prog.cpp:4:16: error: ‘float* Bar::internal(Foo&)’ is protected
         float* internal(Foo& f);
                ^
prog.cpp:11:43: error: within this context
         friend float* Bar::internal(Foo& f);
                                           ^

Answer

rashmatash picture rashmatash · Aug 17, 2014

Well, it should be obvious that you can't access protected/private members of a class from another class. This is also true if you try to friend the protected/private member function. So, you can't do this unless you put the method in a public section or make Foo a friend of Bar.

You can also do this by making the entire class Bar a friend of Foo. So either do this:

class Bar {
protected:
    friend class Foo; // Foo can now see the internals of Bar
    float* internal(Foo& f);
 };
class Foo {
private:
    //some data
public:
    //some methods
    friend float* Bar::internal(Foo& f);
};

Or this:

class Bar {
protected:
    float* internal(Foo& f);
};
class Foo {
private:
    //some data
public:
    //some methods
    friend class Bar; // now Bar::internal has access to internals of Foo
};