Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling functions above their declaration

void foo()
{
    bar();          // error: ‘bar’ has not been declared
}

void bar()
{
}

namespace N
{
    void foo()
    {
        N::bar();   // error: ‘bar’ is not a member of ‘N’
    }

    void bar()
    {
    }
}

class C
{
    static void foo()
    {
        C::bar();   // works just fine
    }

    static void bar()
    {
    }
};

What is the rationale behind this inconsistency of treating calls to functions above their declaration? How come I can do it inside a class, but not inside a namespace or at global scope?

like image 846
fredoverflow Avatar asked Aug 06 '12 09:08

fredoverflow


People also ask

How do you call a function in declaration?

A declared function can be called through its name plus an argument list. The argument list must be enclosed in a () . We often call this as argument passing (or parameter passing). Each single-value argument corresponds to (is passed to) a parameter.

Can we call function before declaration?

However, functions go out of this route as they are read first, but only the function head (= first line). That is why function calls are possible before declaration.

Can I call function before declaration in JavaScript?

With JavaScript functions, it is possible to call functions before actually writing the code for the function statement and they give a defined output. This property is called hoisting. Hoisting is the ability of a function to be invoked at the top of the script before it is declared.

What is the relationship between declaring and calling a function?

declare and define are the same, and they mean when you write all the code for your function. At that point the function just sits there doing nothing. call is when you tell the JavaScript interpreter to run the code in your function.


1 Answers

You can define member functions either inside the class, or after the class declaration, or some of each.

To get some consistency here, the rules for a class with functions defined inline is that it still has to be compiled as if the functions were defined after the class.

Your code

class C {
     static void foo()
     {
         C::bar();   // works just fine 
     }

     static void bar()
     {     }
 }; 

compiles the same as

class C {
     static void foo();
     static void bar();
 }; 

 void C::foo()
 {  C::bar();  }

 void C::bar()
 {     }

and now there is no magic in the visibility, because the functions can all see everything declared in the class.

like image 52
Bo Persson Avatar answered Oct 15 '22 08:10

Bo Persson