John Yang
John Yang

Reputation: 1360

In C++, is there a practical way to restrict the calling of one function to certain function?

C++ does not support nested function. Say I have function a and b, I want to guarantee that only a can call b, and nobody else can, is there a way of doing so?

Upvotes: 3

Views: 835

Answers (4)

Seth Carnegie
Seth Carnegie

Reputation: 75150

There are multiple ways of doing this (none are 100% bulletproof, someone can always edit your source files), but one way would

  1. Put the function inside a class, make it private, and make the functions that you want to have the ability to call it "friends."

  2. Assuming you want function a to be callable by function b but no one else, another way would be to put a and b in their own source file together and make a static. This way, a would only be visible to entities in the same source file, but b would be visible to everyone who had it's signature.

Or 3. If you can use lambdas (i.e. your compiler supports this feature of C++11):

void a() {
    auto f = []() { /* do stuff */ }

    f();
}

Upvotes: 6

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52137

No, but you can always create a function-level class. For example:

void MyFunction() {

    class InnerClass {
    public:
        static void InnerFunction() {
        }
    };

    InnerClass::InnerFunction();
    InnerClass::InnerFunction();
    // ...

};

Upvotes: 2

Xeo
Xeo

Reputation: 131829

The passkey idiom.

class KeyForB{
  // private ctor
  KeyForB(){}
  friend void a();
};

void a(){
  b(KeyForB());
}

void b(KeyForB /*unused*/){
}

Upvotes: 3

Mircea Ispas
Mircea Ispas

Reputation: 20790

int main()
{
    class a
    {
        public:
            static void foo(){}
    };
    a::foo();
}

It compiles fine for me, so you can have "nested functions" in C++

Upvotes: 4

Related Questions