I have created a simple Singleton program. Is has 3 classes: main, Client, and LoginGui.
main.cpp
# include "logingui.h"
# include "client.h"
# include <iostream>
using namespace std;
int main()
{
cout << "Class main()\n";
Client* client = Client::clientInstance();
LoginGui* loginGui = LoginGui::loginGuiInstance();
return 1;
}
# include "logingui.h"
# include "client.h"
# include <iostream>
using namespace std;
int main()
{
cout << "Class main()\n";
Client* client = Client::clientInstance();
LoginGui* loginGui = LoginGui::loginGuiInstance();
return 1;
}
To copy to clipboard, switch view to plain text mode
Client.cpp
# include "logingui.h"
# include "client.h"
# include <iostream>
using namespace std;
Client* Client :: _clientInstance = 0;
Client* Client :: clientInstance()
{
if(_clientInstance == 0)
{
_clientInstance = new Client;
}
return _clientInstance;
}
Client :: Client()
{
cout << "class Client() - Constructor\n";
numberInstances++;
cout << "class Client() - numberInstances: " << numberInstances << "\n";
loginGui = LoginGui::loginGuiInstance();
}
# include "logingui.h"
# include "client.h"
# include <iostream>
using namespace std;
Client* Client :: _clientInstance = 0;
Client* Client :: clientInstance()
{
if(_clientInstance == 0)
{
_clientInstance = new Client;
}
return _clientInstance;
}
Client :: Client()
{
cout << "class Client() - Constructor\n";
numberInstances++;
cout << "class Client() - numberInstances: " << numberInstances << "\n";
loginGui = LoginGui::loginGuiInstance();
}
To copy to clipboard, switch view to plain text mode
LoginGui.cpp
# include "client.h"
# include "logingui.h"
# include <iostream>
using namespace std;
LoginGui* LoginGui:: _loginGuiInstance = 0;
LoginGui* LoginGui:: loginGuiInstance()
{
if(_loginGuiInstance == 0)
{
_loginGuiInstance = new LoginGui;
}
return _loginGuiInstance;
}
LoginGui :: LoginGui()
{
cout << "class LoginGui() - Constructor\n";
numberInstances++;
cout << "class LoginGui() - numberInstances: " << numberInstances << "\n";
client1 = Client::clientInstance();
}
# include "client.h"
# include "logingui.h"
# include <iostream>
using namespace std;
LoginGui* LoginGui:: _loginGuiInstance = 0;
LoginGui* LoginGui:: loginGuiInstance()
{
if(_loginGuiInstance == 0)
{
_loginGuiInstance = new LoginGui;
}
return _loginGuiInstance;
}
LoginGui :: LoginGui()
{
cout << "class LoginGui() - Constructor\n";
numberInstances++;
cout << "class LoginGui() - numberInstances: " << numberInstances << "\n";
client1 = Client::clientInstance();
}
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 ?
Bookmarks