Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

The body of a member function defined inside the definition of a class is a special case: for the purpose of name lookup it is as if the member function was defined immediately after the end of the class definition.

This is why a member function can refer in its definition to other members of the class of which it is a member, regardless where in the class definition it is defined.

Actually, it is called Forward reference

The term forward reference is sometimes used as a synonym of forward declaration. However, more often it is taken to refer to the actual use of an entity before any declaration; that is, the first reference to second in the code above is a forward reference. Thus, we may say that because forward declarations are mandatory in Pascal, forward references are prohibited.

Permitting forward references can greatly increase the complexity and memory requirements of a compiler, and generally prevents the compiler from being implemented in one pass.

It's a different deal when you are talking about definitions within a class (as opposed to the global scope). I believe this is achieved by the compiler passing over the class for definitions first, then looking at the actual implementations of all the methods. To sum up, you do not need to worry about any sort of forward declaration/reference in this case.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top