lundi 15 mai 2023

In C++ Inheritance, Derived class destructor not called when pointer object to base class is pointed to array of derived class

I have an Animal class with constructor and destructor. Cat have a private Brain* attribute. Upon construction, Cat creates his Brain using new Brain(); Upon destruction, Cat deletes his Brain. I don't understand why The cat's and brain's destructors not called, when my Base class destructor is virtual?

#include <iostream>

using std::cout ;
using std::endl ;

class Brain {
public:
    Brain (void){cout << "Brain constructor" << endl ;}
    ~Brain (void){cout << "Brain destructor" << endl ;}
} ;

class Animal
{
public:
    Animal (void){cout << "Animal constructor" << endl ;}
    virtual ~Animal (void){cout << "Animal destructor" << endl ;}
} ;

class Cat : public Animal
{
public:
    Cat (void){
                cout << "Cat constructor" << endl ;
        myPointer = new Brain() ;
    }
    ~Cat (void){
        cout << "Cat destructor" << endl ;
        delete myPointer ;
    }
private:
    Brain* myPointer ;
} ;

int main()
{
    const Animal* j = new Cat[1] ;
    delete [] j ;
}

Gives output

Animal constructor
Cat constructor
Brain constructor
Animal destructor

Aucun commentaire:

Enregistrer un commentaire