Program Execution Before main()
It is impossible to execute a program without main(). The declaration of objects is allowed before main(). We know that when an object is created, constructor and destructor are executed. The constructor can call other member functions. When an object is declared before main(), it is called as global object. For global object, constructor is executed before main() function and destructor is executed after the completion of execution main() function. The following program illustrates this.
9.25 Write a program to declare global object and observe execution of constructor.
Explanation: In the above program, object t is declared before main(). It is a global object. As soon as an object is declared, its constructor is invoked immediately. However, the execution of every program starts from function main(), but for the object declared before main(), constructor is executed before execution of main(). The destructor for such object is executed after the complete execution of function main(). The constructor can invoke other member functions. These member functions are also executed before main(). The following program explains this.
9.26 Write a program to declare object before main() and invoke member function.
Explanation: In the above program, class A is declared with member variable character pointer and integer x. The class also has constructor, destructor, and member function show(). Before main(), object a is declared and constructor is executed that initializes the member variables. The constructor invokes the member function show(). Finally, the destructor is executed.