yes, the constructor of the global object gets called before main()
for additional information:
here I'm listing when the constructors gets called for different types of object like global, local,static local,dynamic
1)for global object you already wrote a program
2)For a non-static local object, constructor is called when execution reaches point where object is declared
using namespace std;
class Test
{
public:
Test();
};
Test::Test() {
cout << "Constructor Called \n";
}
void fun() {
Test t1;
}
int main() {
cout << "Before fun() called\n";
fun();
cout << "After fun() called\n";
return 0;
}
/* OUTPUT:
Before fun() called
Constructor Called
After fun() called
*/
For a local static object, the first time (and only the first time) execution reaches point where object is declared.
3)Class Scope: When an object is created, compiler makes sure that constructors for all of its subobjects (its member and inherited objects) are called. If members have default constructurs or constructor without parameter then these constrctors are called automatically, otherwise parameterized constructors can be called using Initializer List.
// PROGRAM 1: Constrcuctor without any parameter
#include<iostream>
using namespace std;
class A
{
public:
A();
};
A::A() {
cout << "A's Constructor Called \n";
}
class B
{
A t1;
public:
B();
};
B::B() {
cout << "B's Constructor Called \n";
}
int main() {
B b;
return 0;
}
/* OUTPUT:
A's Constructor Called
B's Constructor Called
*/