Shivam Jha
Shivam Jha

Reputation: 88

How do I make a function of a namespace inaccessible by the client side

I'm writing a class which is wrapped in a namespace named cs. I am using a library whose one of the function takes a function pointer. The function have to modify some of the protected members of the class so I wrote a free function in the same cs namespace and made it a friend function of the class. Doing that made it available for the clients to use that function. But The function MUST be inaccessible from the client due to obvious reasons.

An example code is here:

#include "lib.h"
namespace cs{
   class A
   {
     protected:
      int x;
      float y;
      friend int myFunc(void* userdata, int valInt, float valFloat);
     public:
      void abc()
      {
        libFunc(this, myFunc);
      }    
   };
   void myFunc(void *userdata, int x, float y){
       // I would like this function to be inaccessible from the client
       A *obj = (A*) userdata;
       obj->x = x;
       obj->y = y;
     }
}

Upvotes: 2

Views: 309

Answers (1)

Christophe
Christophe

Reputation: 73376

If you want to make a free function inaccessible in another compilation unit, you may use a nested anonymous namespace:

namespace cs{

   class A
   {
     protected:
        //...
        friend int myFunc(int valInt, float valFloat);
     public:
        void abc();
   };

   namespace {  // anonymous nested namespace
        int myFunc(int x, float y){
           ...
     }
   }

   void A:: abc() {
        libFunc(this, myFunc);
   }    
}

Upvotes: 3

Related Questions