InterviewSolution
| 1. |
Write a program that allows to create only one instance of a class? |
|
Answer» This concept is used to create a Singleton Class. Below is CODE snippet demonstrating the same: #include class sample { static sample *PTR ; private: sample( ) { } public: static sample* create( ) { if ( ptr == NULL ) ptr = new sample ; return ptr ; } } ; sample *sample::ptr = NULL ; void main( ) { sample *a = sample::create( ) ; sample *b = sample::create( ) ; }
A static member function CALLED create( ) is used to create an object of the class. In this function the condition is checked WHETHER or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available. |
|