How to call some function before main() function in C++?
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.
- lobal 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:
// C++ program to call some function // before main() function #include <iostream> using namespace std; // Class class GFG { public: // Constructor of the class GFG() { // Call the other function func(); } // Function to get executed before main() void func() { cout << "Inside the other function" << endl; } }; // Global variable to declare // the object of class GFG GFG obj; // Driver code int main() { cout << "Inside main method" << endl; return 0; } |
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 help of 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().
Recommended Posts:
- A C/C++ Function Call Puzzle
- In Java, Can we call the main() method of a class from another class?
- How to call function within function in C or C++
- How to remove error Call to undefined function curl_init()?
- Execute main() multiple times without using any other function or condition or recursion in Java
- Is it fine to write "void main()" or "main()" in C/C++?
- Difference between "int main()" and "int main(void)" in C/C++?
- Difference between Call by Value and Call by Reference
- What does main() return in C and C++?
- Can main() be overloaded in C++?
- Function Overloading vs Function Overriding in C++
- How can we write main as a class in C++?
- return statement vs exit() in main()
- call() decorator in Python
- C/C++ program to print Hello World without using main() and semicolon
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

