2

Ok I'm totally frazzled on this. Code is begin to swim around the screen...must sleep.

So! Ok, troubled by nested classes and friends.

here is the pseudo-code

   class A{
     public:
          //constructor
          // member functions
     private:
          class B{
          //private
          int a();
          };

          class C{
          //private
          int b();
          };
   };

So once an object of type A has been created, I would like it to access a() and b(). I know that I have to use a friend function for this. So where should I put friend class A. Is that the right expression?.

jparthj
  • 1,606
  • 3
  • 20
  • 44

1 Answers1

2

If you would like to access a() and b() from within class A you need to place the friend declaration inside of class B and class C. However, a() and b() are not members of class A so you cannot access them in the way you are thinking. Instead you also need to add forwarding functions to A.

class A
{
public:
    //constructor
    // member functions
private:
    class B
    {
        //private
        int a();

        friend A;    // <-- make A a friend
    };

    class C
    {
        //private
        int b();

        friend A;    // <-- make A a friend
    };

public:

    // forwarding function for a
    int a()
    {
        return bdata_.a();
    }

    // forwarding function for b
    int b()
    {
        return cdata_.b();
    }

private:
    B bdata_;
    C cdata_;
};
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74