Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

About function declarations in functions

We can have function declarations inside of function bodies:

void f(double) {
    cout << "f(double) called";
}

void f(int) {
    cout << "f(int) called";
}

void g() {
    void f(double); //Functions declared in non-namespace scopes do not overload
    f(1);           //Therefore, f(1) will call f(double)                  
}

This can be done in order to hide a function such as f(int) in this case, but my question is: Is this really the only reason why it is possible to declare a function inside of another?

Or in other words:
Does the possibility of declaring a function inside of a function exist for the sole purpose of hiding a function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This can also be used to limit the visibility of a function declaration to only one specific function. For example:

file1.cpp:

#include <iostream>
void f(double d) {
    std::cout << d << '\n';
}

file2.cpp:

int main() {
   void f(double);
   f(1); // prints 1
}

void g() {
    f(2); // error: 'f' was not declared in this scope
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading