Search code examples
c++singletonprivate-constructor

c++ private constructors


If I don't want to allow anyone to create an instance of my class except for my static functions (I think this is called singleton/factory?), is it enough to make the default constructor private, or do I also need to explicitly define and make private a copy constructor and assignment operator?


Solution

  • Yes, I would do all 3 of those manager functions. If not, you do not want to be able to access the copy constructor. For example, this is valid:

    Singleton * s;
    Singleton copy( *s );
    

    So do something like:

    class Singleton
    {
    private:
      Singleton();
      Singleton(const Singleton &);
      Singleton & operator = (const Singleton &);
    };