Reputation: 333
At https://www.studytonight.com/cpp/inline-functions.php they are explaining inline functions
All the inline functions are evaluated by the compiler, at the end of class declaration.
class ForwardReference
{
int i;
public:
// call to undeclared function
int f()
{
return g()+10;
}
int g()
{
return i;
}
};
int main()
{
ForwardReference fr;
fr.f();
}
At the end they say : "You must be thinking that this will lead to compile time error, but in this case it will work, because no inline function in a class is evaluated until the closing braces of class declaration."
......
why should one expect a compile time error? is it because no value for i has been set? If so, could someone explain better why it works, I don't get what's the point here, if the member functions are inline or not wouldn't it work the same?
Upvotes: 2
Views: 221
Reputation: 4991
What they are hinting at here, for why someone might expect a compile error, is the fact that although g
is written below/after f
, f
can still reference it with no error.
If you were to move them out of the class and define+declare them at the same time then you would see the compile error (since f
cannot see any g
).
i.e.
int f(){
return g() + 10;
}
int g(){
return 32;
}
int main(){
return f();
}
See for yourself on compiler explorer.
Upvotes: 1
Reputation: 118350
The book is explicitly pointing out to you "no inline function in a class is evaluated until the closing braces of class declaration". Outside of a class declaration, with ordinary functions, this fails:
int f()
{
return g()+10;
}
int g()
{
return 0;
}
Try to compile a C++ source file containing just this, and nothing more, and see for yourself.
In C++, all functions must be declared before use. Since g()
is not declared, this is ill-formed and your compiler will reject it. g()
must be declared before it's referenced:
int g();
int f()
{
return g()+10;
}
int g()
{
return 0;
}
This does not applly to inline class method because, as your book explains, they are effectively evaluated when the class declaration is complete. At that point both f()
and g()
methods are declared, and the reference from f()
to g()
is well-formed.
Upvotes: 4