Search code examples
c++method-resolution-order

function in C++: define it before use it


In C/C++, the caller function can call the callee function if and only if the callee function is visible to the caller, which means the callee's definition should be done before where it's used, otherwise use forward-declaration.

Here is my problem,

class A
{
    public:
        void foo()
        {
            bar();
        }

        void bar()
        {
            //...
        }
};

int main()
{
    A a;
    a.foo();
}

The above code will work just fine. But foo calls bar and I didn't put bar's definition before foo or forward-declare bar, how could the call to bar in foo work? How could the compiler find bar?


Solution

  • The language says that the scope of a member function declaration is the whole class (loosely), so this is fine.

    What actually happens is that the compiler waits until the end of the class definition (indeed, the end of the outermost enclosing class definition) before attempting to analyse the bodies of the inline functions.

    So it only looks at the call to bar at the end of the class, by which time it has seen its declaration and all is well.