How to avoid memory leak at design-implementation level
<p>
I saw an interview question a couple of days ago regarding memory leaks in c++.
The code was like (if I remember correctly):</p>

<pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
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-&gt;value;
    }
};

class sub : public super {
    int val;
    super sup;
    vector&lt;int&gt; v1;
public:
    sub() :val(0), sup(0) {}
    sub(int value) :val(value), sup(value), v1(10,0) {}
    int getValue() const{
        return this-&gt;val;
    }
};

int main() {
    sub* pt1 = new(sub);
    super* pt2 = pt1;

    pt1 = new(sub);

    delete pt2;     //memory leak ??

    //more code here...
    delete pt1;
    return 0;
}
</code></pre>

<p>The question was how to avoid this type of memory leaks at <strong>implementation-design level</strong>. I guess the question was more than simply answering "do not use pointers like that".</p>

<p>Does it have to do with implementing destructor as virtual or using dynamic cast? How can we implement destructors so that <code>delete pt2</code> wont create any memory leaks? Can anyone further analyze this example?</p>

<p>Thanks in advance.</p>