I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation?
In the following is the code run successfully:
#include "stdafx.h"
#include<stdio.h>
#include <iostream>
using namespace std;
class singleton
{
public:
void print()
{
printf("hello\n");
}
int a;
}singleton;
class client : public singleton
{};
int main()
{
// singleton s; // Can define an object before singleton
// singleton singleton;
// singleton b; #cannot define a new object after singleton
singleton.a=5;
printf("a=%d\n",singleton.a);
singleton.print();
client xyz;
xyz.print();
xyz.a = 10;
cout << "xyz.a = " << xyz.a << endl;
return 0;
}