Possible Duplicate:
Is main() really start of a C++ program?
Is possible to call my function before program's startup? How can i do this work in C++
or C
?
Now, while creating the object with the help of a constructor, the constructor will get executed and the other function will get executed before main() method. Hence we can easily call the function before the main().
The order of functions inside a file is arbitrary. It does not matter if you put function one at the top of the file and function two at the bottom, or vice versa. Caveat: In order for one function to "see" (use) another function, the "prototype" of the function must be seen in the file before the usage.
Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.
You can have a global variable or a static
class member.
1) static
class member
//BeforeMain.h class BeforeMain { static bool foo; }; //BeforeMain.cpp #include "BeforeMain.h" bool BeforeMain::foo = foo();
2) global variable
bool b = foo(); int main() { }
Note this link - Mirror of http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14 / proposed alternative - posted by Lundin.
In C++
there is a simple method: use the constructor of a global object.
class StartUp { public: StartUp() { foo(); } }; StartUp startup; // A global instance int main() { ... }
This because the global object is constructed before main()
starts. As Lundin pointed out, pay attention to the static initialization order fiasco.
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