Baruch
Baruch

Reputation: 21498

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?

Upvotes: 3

Views: 5362

Answers (4)

stefaanv
stefaanv

Reputation: 14392

Making the constuctor private is for the factory method pattern. The singleton pattern needs a factory method.
boost has noncopyable if you don't want your class to be copied, but as James McNellis already commented: decide whether users should be able to copy the class. Because raw pointers and the inherent memory management should not have a place in classes anymore, the question of having classes copied is mostly for classes that use resources or possibly large containers.

Upvotes: 3

Courtney Christensen
Courtney Christensen

Reputation: 9555

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 &);
};

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

If you only want one instance, then yes, the copy constructor should be private. The assignment operator shouldn't matter, because it will be impossible to use anyway.

Upvotes: 0

Diego Sevilla
Diego Sevilla

Reputation: 29011

Yes, usually you have to. If not, you could construct a new object by copy:

MyClass newObject = your_singleton_of_type_MyClass;

In this case the copy constructor is issued, creating two objects actually. Making the copy constructor private prevents the copy by making this code illegal.

Upvotes: 0

Related Questions