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?
4 Answers
There are multiple ways of doing this (none are 100% bulletproof, someone can always edit your source files), but one way would
Put the function inside a class, make it private, and make the functions that you want to have the ability to call it "friends."
Assuming you want function
a
to be callable by functionb
but no one else, another way would be to puta
andb
in their own source file together and makea
static
. This way,a
would only be visible to entities in the same source file, butb
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();
}

- 73,875
- 22
- 181
- 249
-
Note that lambdas are C++11 only. (Perhaps that's why someone downvoted?) – Andrew Marshall Oct 30 '11 at 16:34
-
@AndrewMarshall I don't know why though, I said "If you can use lambdas" – Seth Carnegie Oct 30 '11 at 16:37
-
I don't know who downvoted it (I upvoted it), but I like Branko's method most. It seems that your methods are kind of exotic. – John Yang Oct 30 '11 at 16:47
-
@JohnYang I guess I'm just an exotic kind of a guy. – Seth Carnegie Oct 30 '11 at 16:49
int main()
{
class a
{
public:
static void foo(){}
};
a::foo();
}
It compiles fine for me, so you can have "nested functions" in C++

- 20,260
- 32
- 123
- 211
The passkey idiom.
class KeyForB{
// private ctor
KeyForB(){}
friend void a();
};
void a(){
b(KeyForB());
}
void b(KeyForB /*unused*/){
}
No, but you can always create a function-level class. For example:
void MyFunction() {
class InnerClass {
public:
static void InnerFunction() {
}
};
InnerClass::InnerFunction();
InnerClass::InnerFunction();
// ...
};

- 50,809
- 10
- 93
- 167
-
I don't why other people don't like your solution (can anyone comment?), it seems to me is the easiest and most practical way of doing the job. – John Yang Oct 30 '11 at 16:59