In the previous article, we saw how to execute user defined function before main() in C. In C++ also we can use same mechanism to execute function before main. Here we’ll explore other options in C++.
Execute Function before Main() By Creating Global Object
- Define a class. Call an user defined function from the class constructor.
- Create a global object of that class.
#include <iostream>
void FunBeforeMain() {
std::cout << "FunBeforeMain() called." << std::endl;
}
class C {
public:
C() {
FunBeforeMain();
}
};
C oc;
int main() {
std::cout << "Main started." << std::endl;
return 0;
}
Here is the output of this program.
We can see from this output that the user defined function, FunBeforeMain(), was called even before the main() function started.
In C++, global variables are initialized before main() starts. So as part of global object (oc) initialization, the C class constructor is called. The constructors are also like any other user defined functions. We called the user defined function from the constructor.
By Initializing Static Variable with Return Value of a Function
If we initialize a class static variable with the return value of a user defined function, that function would be called before main().
- Declare a class with a static variable.
- Initialize the static variable with a user defined function.
#include <iostream>
int FunBeforeMain() {
std::cout << "FunBeforeMain() called." << std::endl;
return 0;
}
class C {
public:
static int static_variable;
};
int C::static_variable = FunBeforeMain();
int main() {
std::cout << "Main started." << std::endl;
return 0;
}
Static variables are like global variables. They are initialized before main(). If we initialize a static variable with the return value of a function, the function would be called as part of initialization. Here the static_variable is initialized with the return value of FunBeforeMain(). So FunBeforeMain() is called before main().
The out of this program would be exactly same as the first one.
Initializing Global Variable with Return Value of a Function
Like the previous example, instead of initializing a static variable, we can initialize a global variable with the return value of a function. We’ll have the same effect.
#include <iostream>
int FunBeforeMain() {
std::cout << "FunBeforeMain() called." << std::endl;
return 0;
}
class C {
public:
static int static_variable;
};
int C::static_variable = FunBeforeMain();
int main() {
std::cout << "Main started." << std::endl;
return 0;
}