Search code examples
c++variablesscopegloballocal

Global variable priority over local variable when global function called in scope of local variable c++


I just wanted to clarify a gap in my knowledge.

Given the following code:

I would have expected that "Hi" is printed, based purely on the fact that in the scope of foo, the definition of FuncA is overwritten and hence should be called. This does not happen as shown here https://onlinegdb.com/LzPbpFN3R

Could someone please explain what is happening here?

std::function<void()> FuncA;

void FuncB() {
    if (FuncA) {
        FuncA();
    }
}

struct Foo {
    void FuncA() {
        std::cout << "Hi";
    }
    
    void FuncC() {
        FuncB();
    }
};

int main()
{
    Foo foo{};
    
    foo.FuncC();
    
    return 0;
}

Solution

  • As soon as you call a free function, you are no longer inside the class. And you have lost the special this pointer. A (rather C-ish) way could be:

    void FuncB(struct Foo* a) {   // expect a pointer to a Foo object
        a->FuncA();               // call the method on the passed object
    }
    
    struct Foo {
        void FuncA() {
            std::cout << "Hi";
        }
        
        void FuncC() {
            FuncB(this);         // pass the special this pointer to the function
        }
    };