0

I want to make an inner class a friend of an unrelated class but this doesn't seem to work (at least in gcc 4.1.2):

class A {
    int i;
    friend class B; // fine
    friend class B::C; // not allowed?
};

class B {
    int geti(A* ap) { return ap->i; }

    class C {
        int geti(A* ap) { return ap->i; }
    };
};
dave
  • 21
  • 1
  • 2

1 Answers1

3

You have to declare B::C before using it. The following might work.

Update: Ignoring a usable demonstration as requested, here's a way of structuring this (minus the definitions of member functions) that could work, but bear in mind that everything is private as it stands.

class A;

class B
{
  int geti(A * ap);

public:
  class C
  {
    int geti(A * ap);
  };
};

class A
{
  friend class B;    // fine
  friend class B::C; // fine too
  int i;
};

Then define the getter functions elsewhere:

int B::geti(A * ap) { ... }
int B::C::geti(A * ap) { ... }

Alternative: forward-declare the nested class B::C and save one external definition:

class A;

class B
{
  int geti(const A * ap) const; // we cannot use A yet!

public:
  class C;
};

class A
{
  friend class B;    // fine
  friend class B::C; // fine too
  int i;
};

int B::geti(const A * ap) const { return ap->i; }

class B::C
{
  inline int geti(const A * ap) const { return ap->i; }
};
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • OK that works, thanks, but is there really no way of declaring `B::C` by just doing `class B::C;` in the same way we can do `class B;` to declare `B`? Having to put the getters elsewhere is annoying. – dave Jun 15 '11 at 13:56
  • I posted an alternative, but I don't know if that's better. – Kerrek SB Jun 15 '11 at 14:01
  • 5
    @dave - No, you cannot declare nested names like that. In `class B::C` is B a class or a namespace? – Bo Persson Jun 15 '11 at 14:10
  • @BoPersson: Either it is declared, or it isn't either. Unfortunately it is not allowed even if you say `class B; class B::C`. C++ does not allow forward-declaring member without defining the containing class. – Jan Hudec Aug 07 '13 at 09:19