Contents Up << >>
How can I ensure objects of my class are always created via "new" rather than as locals or global/static objects?
Make sure the class's constructors are "private:", and define
"friend" or
"static" fns that return a ptr to the objects created via "
new" (make the
constructors "protected:" if you want to allow derived classes).
class Fred { //only want to allow dynamicly allocated Fred's
public:
static Fred* create() { return new Fred(); }
static Fred* create(int i) { return new Fred(i); }
static Fred* create(const Fred& fred) { return new Fred(fred); }
private:
Fred();
Fred(int i);
Fred(const Fred& fred);
virtual ~Fred();
};
main()
{
Fred* p = Fred::create(5);
...
delete p;
}
Debugging and error handling