What is the best practice associated with memory allocation?
If I add a delete function to my destructor to a class with memory allocated pointers, when would the destructor actually initiate and delete the memory?
For example I have something like:
1 2 3 4 5 6 7 8 9
class A {
public:
int *p = newint [10]
A(){p[0]=1;p[1]=2;}
~A(){ delete [] p; }
};
But, the variables in class A are inherited to other classes. How can I make sure to delete the memory after all classes have used the variables?
virtual functions aren't required for Liskov substitution.
That is, it's still possible to treat a derived as a base and run into problems, even if this is less likely when other virtual functions aren't involved.
In any event, OP's class is contrived, and I figured a reminder was in order. Personally I forget to declare my destructors virtual way too often.
What is the best practice associated with memory allocation?
Decide who owns the memory (who deletes it). Document that in your comments and code to that standard. If you do this then memory management isn't hard.
You can also just use unique_ptr<> and shared_ptr<>
That is, it's still possible to treat a derived as a base and run into problems [by not having virtual destructors]
Oh, I think I see what you're saying now. I never thought about that.
1 2
Base* base = new Derived;
delete base;
Will only call the Base destructor if Base's dtor is not virtual, but will call both the Derived and Base destructor (in that order) if it's virtual (which sounds obvious in hindsight, though, as you said, this is kinda weird to do if the Base class can't be used polymorphically for any other purpose anyway.)