tags:

views:

99

answers:

2

Hi, I have a class inside a namespace and that class contains a private function. And there is a global function. I want that global function to be the friend of my class which is inside the namespace. But when I make it as a friend, the compiler thinks that the function is not global and it is inside that namespace itself. So if I try to access the private member function with global function, it doesn't work, whereas if I define a function with the same name in that namespace itself it works. Below is the code you can see.

#include <iostream>
#include <conio.h>

namespace Nayan
{
   class CA
   {
   private:
      static void funCA();
      friend void fun();
   };

   void CA::funCA()
   {
      std::cout<<"CA::funCA"<<std::endl;
   }

   void fun()
   {
      Nayan::CA::funCA();
   }

}

void fun()
{
   //Nayan::CA::funCA(); //Can't access private member
}


int main()
{
   Nayan::fun();
   _getch();
   return 0;
}

I also tried to make friend as friend void ::fun(); And it also doesn't help.

+10  A: 

You need to use the global scope operator ::.

void fun();

namespace Nayan
{
    class CA
    {
    private:
        static void funCA();
        friend void fun();
        friend void ::fun();
    };

    void CA::funCA()
    {
        std::cout<<"CA::funCA"<<std::endl;
    }

    void fun()
    {
        Nayan::CA::funCA();
    }

}


void fun()
{
   Nayan::CA::funCA(); //Can access private member
}
Brian R. Bondy
@Brian I believe what compilernayan intends is to declare fun() outside the Nayan namespace.
Vitor Py
@Vitor Py: Ya I know but it doesn't hurt to show the difference explicitly. Each friend refers to something different.
Brian R. Bondy
+2  A: 

The fun() function is in the global namespace. You need a prototype:

void fun();

namespace Nayan
{
    class CA
    {
    private:
        static void funCA() {}
        friend void ::fun();
    };

}

void fun()
{
    Nayan::CA::funCA();
}
Hans Passant