Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit a function scope in the same file as it is defined in c++?

Tags:

c++

namespaces

I have public member functions which are calling private member function. I want to limit the scope of the private member function within the file where definition of private member function is available. In C, I used static before the function name to limit its scope within the file, how do I achieve it in C++.

class Base
{
  public:
  void XYZ1(void);
  void XYZ2(void);
  private:
  void fun(void);
};

void Base::XYZ1(void)
{
  fun();
}

void Base::fun(void)
{
  // do something;
}

Now if the member function XYZ2 is defined in some other .cpp file , it should not be allowed to call fun() from it. Basically restrict the fun() function to file scope. In a1.cpp

void Base::XYZ2(void)
{
  fun();// this should result in some error saying fun() is not defined in its scope.
}
like image 695
Dipanjan Avatar asked Sep 13 '25 18:09

Dipanjan


1 Answers

I want to limit the scope of the private member function within the file where definition of private member function is available.

A private member function cannot be used by another class or function unless they are granted friend-ship by the class. In that sense, the scope in which the function can be called is already limited.

Having said that, any member function of the class or any class or function that has been granted friend-ship by the class will be able to call the private member function.

The only way to prevent that function from being called outside the file in which it is defined is to make it a non-member static function in the .cpp file. or put it in an anonymous namespace in the .cpp file.

like image 150
R Sahu Avatar answered Sep 16 '25 08:09

R Sahu