Possible Duplicate:
How do I prevent a class from being allocated via the 'new' operator? (I'd like to ensure my RAII class is always allocated on the stack.)
Suppose I define a class in the library
class Base {};
and I publish the class to the users.
And one user defines a new class
class Derived : public Base {}
The question what can I do in Base to prevent users create an instance of Derived on heap?
For example, this is allowed
Derived dd;
This is not
Derived* dd = new Derived();
Thanks,
I think the best you can do is to declare a
privateoperator new(I can’t recall if this is needed but you’ll probably want to do all three: normal, array, and placement) in your base class. The user can still get around this by creating their ownoperator newin the Derived class but at least they have to think about it and actively work to subvert your intention.If you’re worried about non-accidental problems with creating your class on the heap (for example malicious developers of child classes), C++ is not the language for this project. It’s powerful and has lots of places where your have to rely on your end-programmers not bypassing the intentions.