LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ class-object? (https://www.linuxquestions.org/questions/programming-9/c-class-object-274473/)

shivaligupta 01-06-2005 01:51 AM

C++ class-object?
 
In C++, How one can restrict a class so tht it can have oly one object?

bm17 01-06-2005 02:20 AM

You can't, really. But you can, effectively. The question you need to ask is "What do I want to see happen when the code attempts to create a second instance?".

Still, this situation does arise often enough and is usually handled through the use of static class variables. For more information do a google search on "c++ singleton pattern".

Hivemind 01-06-2005 02:25 AM

What you want is known as a singleton and in a singleton class the constructor is private.
Instead you have a public static member function that returns a dynamically allocated instance
of the class and this instance is a static data member of the class itself.

Code:

class mysingleton
{
public:
  static mysingleton* get_instance()
  {
      if(!instance)
        instance = new mysingleton(/*arguments*/);
      return instance;
  }
private:
  mysingleton(/*arguments*/);
  static mysingleton *instance;
};

mysingleton* mysingleton::instance=NULL;

Use google to search for singleton (pattern) to learn more.


All times are GMT -5. The time now is 04:49 PM.