Question and Answer Database FAQ4347C.txt :How can I have a class which allows only one object to be created? Category :C/C++ Language Issues Platform :All Product :All, Question: How can I have a class which allows only one object to be created? Answer: There are several ways of doing this. If you want want the ability to set a limit on the number of objects that can be created, consider reference counting: class TFoo { private: static int FCount; public: TFoo() { if (FCount> 0) throw ESomeException; FCount++; } ~TFoo() { FCount--; } }; int TFoo::FCount = 0; If you want to have one and only one object ever be created then consider the following: class TFoo { private: static int FCount; public: TFoo() { static int count = 0; if (count> 0) throw ESomeException; count++; } ~TFoo() {} }; 2/10/1999 3:01:24 PM
Last Modified: 01-SEP-99