Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friend function in derived class with private inheritance

If a class Derived is inherited privately from a class Base and the Derived class has a friend function f(), so what members can f() access from Derived class and Base class.

class Base {
public:
    int a;
protected:
    int b;
private:
    int c;
};  


class Derived: private Base {    
    void friend f() {}

public:
    int d;
protected:
    int e;
private:
    int f;
};

I understand that if a class is inherited privately from the base class, everything is private in the derived class.

But why in the code above, the function f() can access a, b, d, e, f but not c?

like image 412
skydoor Avatar asked Jan 26 '10 21:01

skydoor


4 Answers

'Friendship' grants access to the class that declares the friend - it's not transitive. To use a bad analogy - my friends are not necessarily my dad's friends.

The C++ FAQ has a bit more detail:

  • http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4
like image 148
Michael Burr Avatar answered Nov 12 '22 05:11

Michael Burr


A friend of Derived can access exactly what Derived itself can - that is, any member of Derived, and any public or protected member of any base class, or of any public or protected grand-parent class, but not any private members of base classes, or members of private grand-parent classes.

like image 44
Mike Seymour Avatar answered Nov 12 '22 07:11

Mike Seymour


Private members are not accessible in derived classes.

like image 2
Anon. Avatar answered Nov 12 '22 05:11

Anon.


The friend function has access to all members of Derived. It doesn't have access to any members of Base that Derived can't access. Derived can't access Base::c because Base::c is private.

like image 2
Liz Albin Avatar answered Nov 12 '22 06:11

Liz Albin