I'm getting strange behavior from c++ constructors and need clarification please. Recently, I wanted to make use of the Singleton pattern. After searching online for examples and modifying the code to meet my need, I ran into an unexpected behavior. Simply the consturctors are called before main() starts. To save you time going over the code, which is 4 classes. I simply have, main.cpp, First.cpp, Second.cpp, Third.cpp and Singleton.cpp.
In main.cpp
int main()
{
cout << "Inside main()" << endl;
cout<<"val = "<<Singleton::Instance()->callThem()<<endl;
delete Singleton::Instance();
return 0;
}
The sequence of calls is: main() -> Singleton::callThem() -> First::callFirst() -> Second::callSecond() -> Third::callThird()
Singleton.cpp
#include "singleton.h"
#include <iostream>
First first; //source of the problem
Singleton::Singleton()
{
std::cout<<"Singleton Constructor"<<std::endl;
}
Singleton::~Singleton()
{
std::cout<<"Singleton Destructor"<<std::endl;
}
Singleton* Singleton::m_pInstance = NULL;
Singleton* Singleton::Instance()
{
if (!m_pInstance)
{
m_pInstance = new Singleton;
}
return m_pInstance;
}
int Singleton::callThem()
{
return first.callFirst();
}
The output as follows:
Third Constructor
Second Constructor
First Constructor
Inside main()
Third Constructor
Second Constructor
First Constructor
Singleton Constructor
val = 3
Singleton Destructor
First Destructor
Second Destructor
Third Constructor
First Destructor
Second Destructor
Third Constructor
How can constructors be called before Inside main()
? Isn't main() where execution begins?
If I remove First first; //source of the problem
, the first line that prints out is Inside main()
, no constructors called before main(). Would appreciate your clarification.