Preventing an instance of an object outside its factory method

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 creation of an instance of an object of this class with new, so that the factory method is the only method for creating an instance of the object?

+5
source share
2 answers

Of course; just make the constructor private (protected if it is a base class):

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

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

You should also make the copy constructor private / secure, if necessary.

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

+8
source

, , , ++ 11, , , - :

struct NonCopyable {
    NonCopyable & operator=(const NonCopyable&) = delete;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable() = default;
};

class A : NonCopyable {
public:
  static std::shared_ptr<A> newA()
  {
    // Some code, logging, ...
    return std::make_shared<A>();
  }

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

++ 03 :

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

private:
  A() {}                        // no outsider default constructor
  A(const A& rhs);              // no copy
  A& operator=(const A& rhs);   // no assignment
};

int main()
{
    A x;        // C2248
    A y(x);     // C2248
    x = y;      // C2248
    A* p = A::newA(); // OK
    std::cin.get();
    return 0;
}
+3

All Articles