Since it is known that main() method is the entry point of the program. Hence it is the first method that will get executed by the compiler. But this article explains how to call some function before the main() method gets executed in C++.
How to call some function before main() function?
To call some function before main() method in C++,
- Create a class
- Create a function in this class to be called.
- Create the constructor of this class and call the above method in this constructor
- Now declare an object of this class as a global variable.
- Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.
Below is the implementation of the above approach:
Inside the other function Inside main method
How will this get executed?
Now when the program will get executed, the global variable will get created before calling the main() method. 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().