Why simple destructor does not delete the derived object if declared using base pointer

后端 未结 4 1933
清酒与你
清酒与你 2021-01-25 12:11
int main()
{

    Base *p = new Derived;
    delete p;
    return 0;
}

I have some confusion, why deleting p here won\'t delete the derived object ? Is

4条回答
  •  孤街浪徒
    2021-01-25 12:46

    You should declare a virtual destructor:

    class Base {
       //etc...
       virtual ~Base();
    };
    
    class Derived {
       //etc...
       virtual ~Derived();
    };
    
    Base* p = new Derived();
    delete p;
    

    (Of course many things are missing above, including constructors)

提交回复
热议问题