-1

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?

Trizion
  • 262
  • 1
  • 12
  • 2
    Why do you not respect SO users, that have to add missing #include, namespaces and main() for getting your code compiled? – 273K Jul 22 '22 at 16:47
  • 1
    Backward compatibility with `C` – Jason Jul 22 '22 at 16:53
  • "Backward compatibility with C" Could you explain this? This specific issue revolves around declaring an overloaded function, function overloading is not supported by C. – Trizion Jul 22 '22 at 17:05
  • "Why do you not respect SO users" I didn't actually think that anyone wanted to compile and run the code, but I should have considered that. I apologize if you felt disrespected. – Trizion Jul 22 '22 at 17:06
  • @Trizion Essential reading: the [tour], [ask] and what is a [mre]. – Paul Sanders Jul 22 '22 at 17:21
  • Also, just so you know, I would say that the C++98 tag is not appropriate here. What you're talking about applies to all versions of C++. Sorry if this sounds a bit picky, but the way tags are used is important to people. – Paul Sanders Jul 22 '22 at 17:23
  • I chose the C++98 Tag because the reason for this question, as well as most of the code posted here come from a book refering to the ISO/IEC 14882 C++ 98 Standard. – Trizion Jul 22 '22 at 17:27
  • Being in a function is a red herring. Names declared in different scopes do not overload. The curly braces in the function define a scope. You could define an inner scope inside your function with additional curly braces and declare functions there, too. – Pete Becker Jul 22 '22 at 20:43

1 Answers1

1

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
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Basically same as [this answer](https://stackoverflow.com/a/33102815/12002570). – Jason Jul 22 '22 at 16:57
  • Thanks, I dont agree with whoever decided that these other threads answer my questions, since they do not include your answer. – Trizion Jul 22 '22 at 17:00