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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With