Sometimes restriction of object storage is usefull.
The following class could be created only by new operator in the heap. This is important when new takes extra parameters, or defines special semantics: like persistency or garbage collection.
// // Objects only in heap: // #include <new> class X { public: X() {} void destroy() const { delete this; } protected: ~X() {} }; class Y : public X { }; // class Z { X xx; }; // use pointer!
The usage:
// X x1; int main() { // X x2; // Y y1; X* xp = new X; Y* yp = new Y; // delete xp; xp->destroy(); delete yp; };
It is still possible to create objects of X and Y in the stack or as static variable. We can define placement new the same way as we did with new.