I saw an interview question a couple of days ago regarding memory leaks in c++. The code was like (if I remember correctly):
#include <iostream>
using namespace std;
class super {
int value;
int arr[1000];
public:
super() :value(0) {}
super(int value) :value(value) {}
virtual int getValue() const{
return this->value;
}
};
class sub : public super {
int val;
super sup;
vector<int> v1;
public:
sub() :val(0), sup(0) {}
sub(int value) :val(value), sup(value), v1(10,0) {}
int getValue() const{
return this->val;
}
};
int main() {
sub* pt1 = new(sub);
super* pt2 = pt1;
pt1 = new(sub);
delete pt2; //memory leak ??
//more code here...
delete pt1;
return 0;
}
The question was how to avoid this type of memory leaks at implementation-design level. I guess the question was more than simply answering "do not use pointers like that".
Does it have to do with implementing destructor as virtual or using dynamic cast? How can we implement destructors so that delete pt2
wont create any memory leaks? Can anyone further analyze this example?
Thanks in advance.