I have created a simple Singleton program. Is has 3 classes: main, Client, and LoginGui.

main.cpp
Qt Code:
  1. # include "logingui.h"
  2. # include "client.h"
  3. # include <iostream>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. cout << "Class main()\n";
  9. Client* client = Client::clientInstance();
  10. LoginGui* loginGui = LoginGui::loginGuiInstance();
  11. return 1;
  12. }
To copy to clipboard, switch view to plain text mode 

Client.cpp
Qt Code:
  1. # include "logingui.h"
  2. # include "client.h"
  3. # include <iostream>
  4. using namespace std;
  5.  
  6. Client* Client :: _clientInstance = 0;
  7.  
  8. Client* Client :: clientInstance()
  9. {
  10. if(_clientInstance == 0)
  11. {
  12. _clientInstance = new Client;
  13. }
  14. return _clientInstance;
  15. }
  16.  
  17.  
  18. Client :: Client()
  19. {
  20. cout << "class Client() - Constructor\n";
  21. numberInstances++;
  22. cout << "class Client() - numberInstances: " << numberInstances << "\n";
  23. loginGui = LoginGui::loginGuiInstance();
  24. }
To copy to clipboard, switch view to plain text mode 

LoginGui.cpp
Qt Code:
  1. # include "client.h"
  2. # include "logingui.h"
  3. # include <iostream>
  4. using namespace std;
  5.  
  6. LoginGui* LoginGui:: _loginGuiInstance = 0;
  7.  
  8. LoginGui* LoginGui:: loginGuiInstance()
  9. {
  10. if(_loginGuiInstance == 0)
  11. {
  12. _loginGuiInstance = new LoginGui;
  13. }
  14. return _loginGuiInstance;
  15. }
  16.  
  17. LoginGui :: LoginGui()
  18. {
  19. cout << "class LoginGui() - Constructor\n";
  20. numberInstances++;
  21. cout << "class LoginGui() - numberInstances: " << numberInstances << "\n";
  22.  
  23. client1 = Client::clientInstance();
  24. }
To copy to clipboard, switch view to plain text mode 


The pattern is suppose to create only one instance of a class, but when the Client class calls the LoginGui class, it ends in recursion.

Why ?