views:

775

answers:

3

Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?

+3  A: 

You could make the constructor private, then provide a public static factory method to create the objects.

Jason Cohen
+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
+1 for remembering to make it uncopyable.
Steve Jessop
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;
}