The constructors of globally declared classes are invoked before main is entered. While this can be confusing to a new reader of the code because it is done so infrequently, is it necessarily a bad idea?
For most C and C++ programs, the true entry point is not main , it's the _start function. This function initializes the program runtime and invokes the program's main function. The use of _start is merely a general convention. The entry function can vary depending on the system, compiler, and standard libraries.
In object-oriented languages (C++) you can execute code before main() by using a global object or a class static object and have their constructors run the code you want.
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 function main is always compiled first, regardless of where in the program the function main is placed. Using functions greatly enhances a program's readability because it reduces the complexity of the function main.
It's not necessarily a bad idea, but usually, yes.
First, it's global data, and globals are usually a bad thing. The more global state you have, the harder it becomes to reason about your program.
Second, C++ doesn't guarantee intialization order of static objects defined in different translation units (.cpp files) -- so if they depend on one another, you might be in trouble.
Yes, this is bad. Since you will have no way to catch exceptions and deal with them, the default handler will be used. In C++ that means calling terminate...
Example: contents a.cpp
#include <stdexcept>
int f() { throw std::runtime_error("boom"); return 42; }
int i = f();
int main(int argc, char* argv[])
{
return 0;
}
Output of : g++ a.cpp && ./a.out
terminate called after throwing an instance of 'std::runtime_error'
what(): boom
Aborted (core dumped)
You can try add a try ... catch
in your main, that won't help.
Edit: Jalf's points are valid too. Listen to his advice.
In addition to being of questionable form - It will not be portable to some platforms.
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