Does delete on a pointer to a subclass call the base class destructor?

前端 未结 11 2191
面向向阳花
面向向阳花 2020-11-27 09:16

I have an class A which uses a heap memory allocation for one of its fields. Class A is instantiated and stored as a pointer field in another class (clas

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 09:32

    no it will not call destructor for class A, you should call it explicitly (like PoweRoy told), delete line 'delete ptr;' in example to compare ...

      #include 
    
      class A
      {
         public:
            A(){};
            ~A();
      };
    
      A::~A()
      {
         std::cout << "Destructor of A" << std::endl;
      }
    
      class B
      {
         public:
            B(){ptr = new A();};
            ~B();
         private:
            A* ptr;
      };
    
      B::~B()
      {
         delete ptr;
         std::cout << "Destructor of B" << std::endl;
      }
    
      int main()
      {
         B* b = new B();
         delete b;
         return 0;
      }
    

提交回复
热议问题