arunmoezhi arunmoezhi - 1 month ago 4
C++ Question

protected destructor object allocation on heap vs stack

If a destructor is protected, why allocating an object on stack not allowed, but allocating on a heap is allowed?

class Foo

int main()
Foo* objOnHeap = new Foo(); // compiles fine
Foo objOnStack; // complains that the destructor is protected
return 0;


When you create an object with automatic storage duration (the standard term for what you call "on the stack"), it is implicitly destroyed when the object goes out of scope. This requires a publicly accessible destructor. When you allocate an object dynamically with new, this does not happen. The dynamically allocated object is only destroyed if you do it explicitly (e.g. with delete). You aren't trying to do that, so you don't get an error. You would get an error if you did this:

delete objOnHeap;