c+ - Quand utiliser des destructeurs virtuels

Mots clés : c++polymorphismshared-ptrvirtual-destructorc++

meilleur 2 Réponses c+ - Quand utiliser des destructeurs virtuels

vote vote

99

class Base  {     // some virtual methods };  class Derived : public Base {     ~Derived()     {         // Do some important cleanup     } }; 
Base *b = new Derived(); // use b delete b; // Here's the problem! 
vote vote

82

#include <iostream>  using namespace std;  class Base { public:     Base(){         cout << "Base Constructor Called\n";     }     ~Base(){         cout << "Base Destructor called\n";     } };  class Derived1: public Base { public:     Derived1(){         cout << "Derived constructor called\n";     }     ~Derived1(){         cout << "Derived destructor called\n";     } };  int main() {     Base *b = new Derived1();     delete b; } 
Base Constructor Called Derived constructor called Base Destructor called 
#include <iostream>  using namespace std;  class Base {  public:     Base(){         cout << "Base Constructor Called\n";     }     virtual ~Base(){         cout << "Base Destructor called\n";     } };  class Derived1: public Base { public:     Derived1(){         cout << "Derived constructor called\n";     }     ~Derived1(){         cout << "Derived destructor called\n";     } };  int main() {     Base *b = new Derived1();     delete b; } 
Base Constructor Called Derived Constructor called Derived destructor called Base destructor called 

Questions similaires