Considering class A, I would like to limit its creation to new. That is
A* a = new A; // Would be allowed.
A a; // Would not be allowed.
How could this be accomplished?
Considering class A, I would like to limit its creation to new. That is
A* a = new A; // Would be allowed.
A a; // Would not be allowed.
How could this be accomplished?
You could make the constructor private and provide a static
factory method that returns a dynamically allocated instance:
class A
{
public:
static A* new_instance() { return new A(); }
private:
A() {}
};
Instead of returning a raw pointer, consider returning a smart pointer instead:
class A
{
public:
static std::shared_ptr<A> new_instance()
{
return std::make_shared<A>();
}
private:
A() {}
};
One option is to make the constructor(s) private, and use a static helper function:
class A {
private:
A() {} // Default constructor
A(const A &a); // Copy constructor
public:
static A *create() { return new A; }
};
...
A a; // Won't compile
A *p = A::create(); // Fine
Although you should strongly consider returning a smart pointer rather than a raw pointer.
Yes, you can do so using the factory pattern.
class A
{
A() {} //private by default
friend struct AFactory;
};
struct AFactory
{
static A* newA() { return new A; }
};
or a similar static
member function.
This is actually very simple. Make your destructor private. Objects with private destructors cannot be created on the stack, so the only way to create them is via a call to "new". You'll need to provide another mechanism for deleting the object, such as a "delete()" method that calls "delete self".
I assume you are trying to control what a client can do with your class. The answers here make use of slightly arcane techniques. A common way of segregating systems is to use interfaces.
You could make A abstract:
class A
{
public:
virtual void doSomething() = 0;
virtual ~A() {}
};
And make at least one implementation:
class A_impl : public A
{
public:
virtual void doSomething()
{
// behaviour
}
};
Then return an instance of A_impl
to the client using a (smart)pointer as the other answers suggest.
Can you not just do:
A* a;
? That is just declaring a pointer to an A
object. It hasn't been initialised though so you should probably do
A* a = NULL;
That is a pointer to an object of type A
but points to a known (non)value.
EDIT: Perhaps I'm not grasping the full question given the complexity of the other answers here.
EDIT2: Is he asking if you can prevent creation of object on the stack and only allow heap created objects and access via pointers? If that is the case my vote goes to a factory pattern.