Prevent instantiation of an object outside its factory method

c++, factory-pattern, oop

Solution

Sure; just make the constructor private (protected if this is a base class):

class A {
public:
  static A* newA()
  {
    // Some code, logging, ...
    return new A();
  }

private:
  A() {}  // Default constructor
};

You should make the copy constructor private/protected as well, if required.

And as always, you should strongly consider returning a smart pointer rather than a raw pointer, in order to simplify memory management issues.

Problem

Suppose I have a class with a factory method ``` class A { public: static A* newA() { // Some code, logging, ... return new A(); } } ``` Is it possible to prevent the instantiation of an object of this class with a `new`, so that factory method is the only method to create an instance of the object?

Original source