开发者

Delete memory in inheritance

I have code below, it always has memory leak please help me.

Thanks, Ankata


 class ABCD
{
public:
    ABCD(void);
    ~ABCD(void);

    CString tem1;
    CString tem2;
};

class CDE :
    public ABCD
{
public:
    CDE(void);
    ~CDE(void);
    CString tem;
};
开发者_运维技巧
void main()
{
        CList<ABCD*> m;
        CDE *a = new CDE();

        a->tem1 = "AAA";
        a->tem2 ="BBB";
        a->tem ="CCC";

        m.AddTail(a);

        ABCD *b = m.GetTail();
        delete b;   
}


Your destructor for class ABCD is not virtual so by casting the pointer to base class type, it will not call the destructor of the derived one thus not freeing memory allocated in CDE.


The destructor for ABCD needs to be virtual.


Your ABCD destructor should be virtual for one, if you're going to use the base class pointer to delete the class


There are a lot of problems with this code, and we don't have definitions, so hard to know what's specifically wrong.

  1. When using inheritance, unless you know what you are doing, make destructors virtual. In your specific case, the ABCD destructor will be called, not the CDE one as it should

  2. Don't delete b unless you are also removing it from m. If not, m contains a dangling pointer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜