Hi
I have a class
Derived
which implements an interface
Base
, something like this
class Base {
public:
virtual void foo () = 0;
};
class Derived : public Base {
public:
Derived (int i = 5) {
data = new double [i];
}
~Derived () {
foo ();
}
void foo () {
if (data) {
delete []data;
}
}
private:
double *data; };
The foo here as you can see does the cleaning up routine. Now I create an instance of class
Derived
and store it to variable of type
Base
:
int n;
Base *base;
n = 1024 * 1024 * 8; base = new Derived (n);
delete base;
After this, the used resources still not reclaimed, although the variable
base
is already invalid. I notice that It doesn't even go to the destructor of
~Derived()
hence the resources is still there. I don't know why, maybe someone can explain this.
After a little while I come up with a solution:
int n;
Base *base;
n = 1024 * 1024 * 8;
base = new Derived (n);
Derived *p;
p = dynamic_cast<Derived*>(base);
if (p) {
delete p;
}
Are there any other solution than this?