Function hide or overload question, about scope, overload

we all know if there are

1
2
3
4
5
6
7
8
void print(double); //defined globally

and then
void fooBar(int ival)
{
    void print(int); //local funtion
    print(3.14); // will call the local function
}


this is very clear for me. But if we have several layers of local, then what?

for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void print(double); //global

void fooBar(int ival)
{
    void print(int); // local layer 1    
    void foo();
    
    print(3.14); //call local layer 1 print
}

    void foo(); //local layer 2
    {
        print(3.14);  //which one to call?
        print(3);   // which one to call?
    }

questions is which one to call the print(double) or print(int)? would the compiler stop searching for global area if it find one in a nearest local area?
Last edited on
would the compiler stop searching for global area if it find one in a nearest local area?

yes, unqualified name lookup stops as soon as it examines a scope with a matching name, and does not proceed to the enclosing scope.

Here are some details: http://en.cppreference.com/w/cpp/language/lookup


However, you are wrong in your premises about 'local functions' and 'local layers' - they do not exist in C++. What you have are block-scope declarations of functions that are defined at namespace scope.

Here's your second program made compilable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
void print(double);  // name 'print' declared at namespace scope
void fooBar(int ival)
{
    void print(int); //  name 'print' declared at block scope
    void foo(); // name 'foo' declared at block scope (and unused)

    print(3.14); // name 'print' from the block scope is found
                 // lookup does not proceed to namespace scope
                 // this compiles a call to void print(int)
}

void foo()
{
    print(3.14);  // name 'print' is not declared at this block scope
                  // so lookup proceeds to namespace scope
                  // this compiles a call to void print(double)
    print(3);     // same.
}

int main()
{
            fooBar(1);
            foo();
}
void print(double) { std::cout << "d\n"; }
void print(int ) { std::cout << "i\n"; }


demo: http://coliru.stacked-crooked.com/a/072f3c454e109156
Last edited on
Thanks, Cubbi! That helps!
Topic archived. No new replies allowed.