Need help to understand Singleton class functionality

I have written code to understand the functionality of Singletom Class, by defintion -- singleton is one instance of a class and user of singleton doesn't have possibility to create another one. However, in my code I am able to create two instances of a Class. I would appreciate, if you can help me understand the basic concept through my code. Thank you very much..

class Rectangle
{
private:
int width, height;
static Rectangle* rectangle;
static bool instance_flag;
Rectangle(){}
~Rectangle(){}

public:
static Rectangle* getInstance();
int rectArea(void);
};

bool Rectangle::instance_flag = false;
Rectangle* Rectangle::rectangle = NULL;

Rectangle* Rectangle::getInstance()
{
if (!instance_flag)
{
rectangle = new Rectangle();
instance_flag= true;
return rectangle;
}
else return rectangle;

}

int Rectangle::rectArea()
{
width = 5, height = 10;
return width * height;
}


void main(void)
{
Rectangle *sc1 = Rectangle::getInstance();//one instance
Rectangle *sc2 = Rectangle::getInstance();//second instance

cout << "Rectangle Area is :" << sc1->rectArea() << endl;
cout << "Rectangle Area is :" << sc2->rectArea() << endl;
}




You've not created two instances. You've created two pointers that point to the same (singleton) instance.

Add the following two lines to confirm that both pointers point to the same thing.
1
2
	cout << "@sc1= " << sc1 << endl;
	cout << "@sc2= " << sc2 << endl;


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Last edited on
Thanks AbstractionAnon.. I got it.. Sorry about not following the format while posting the code. Best Regards
Topic archived. No new replies allowed.