gerdi
gerdi

Reputation: 165

Why does GCC not allow inheriting from a private nested class when you are a friend?

Same question is asked: Why does GCC allow inheriting from a private nested class? For non template classes, its allowed to inherit from private nested classes, if it is a friend, but not for template classes. Is it a bug?

template<class Base>
class InheritFromBaseMember : public Base::MemberPrivate // error
{
    using PrivateMember = typename Base::MemberPrivate; // works fine
};

class MyBase{
    friend class InheritFromBaseMember<MyBase>;

    // another try to declare it friend
    template<class T>
    friend class InheritFromBaseMember;

    friend class AnotherClass;

    class MemberPrivate{};
};

class AnotherClass : public MyBase::MemberPrivate{}; // works fine

int main() {
    InheritFromBaseMember<MyBase>{};
}

Errormessage from g++ 5.3.0:

error: 'class MyBase::MemberPrivate' is private
     class MemberPrivate{};
           ^
error: within this context
 class InheritFromBaseMember : public Base::MemberPrivate // error
       ^

Upvotes: 9

Views: 195

Answers (1)

Barry
Barry

Reputation: 303107

This is definitely a gcc bug. gcc has lots of issues with friendship and templates. This example almost exactly appears in the standard, under [class.friend], emphasis mine:

Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class.
[ Example:

class A {
class B { };
    friend class X;
};

struct X : A::B { // OK: A::B accessible to friend
    A::B mx;      // OK: A::B accessible to member of friend
    class Y {
        A::B my;  // OK: A::B accessible to nested member of friend
    };
};

—end example ]

Upvotes: 6

Related Questions