Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?
views:
775answers:
3
+3
A:
You could make the constructor private
, then provide a public
static factory method to create the objects.
Jason Cohen
2008-09-24 01:31:50
+27
A:
One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:
class Foo
{
public:
~Foo();
static Foo* createFoo()
{
return new Foo();
}
private:
Foo();
Foo(const Foo&);
Foo& operator=(const Foo&);
};
Daemin
2008-09-24 01:32:04
+1 for remembering to make it uncopyable.
Steve Jessop
2008-09-24 01:34:06
A:
You could create a header file that provides an abstract interface for the object, and factory functions that return pointers to objects created on the heap.
// Header file
class IAbstract
{
virtual void AbstractMethod() = 0;
public:
virtual ~IAbstract();
};
IAbstract* CreateSubClassA();
IAbstract* CreateSubClassB();
// Source file
class SubClassA : public IAbstract
{
void AbstractMethod() {}
};
class SubClassB : public IAbstract
{
void AbstractMethod() {}
};
IAbstract* CreateSubClassA()
{
return new SubClassA;
}
IAbstract* CreateSubClassB()
{
return new SubClassB;
}