/*
use virtual destructors in polymorphic base classes
*/
//方案一
class Dog
{
public:
virtual ~Dog()
{
cout << "Dog destroyed" << endl;
}
virtual void bark() {}
};
class Yellowdog : public Dog
{
public:
~Yellowdog() { cout << "Yellow dog destroyed" << endl; }
};
class DogFactory
{
public:
static Dog* creatYellowDog()
{
return (new Yellowdog());
}
//...creat other dogs
};
int main()
{
Dog* pd = DogFactory::creatYellowDog();
//..Do something with pd
delete pd;
return 0;
}
//方案二
class Dog
{
public:
~Dog()
{
cout << "Dog destroyed" << endl;
}
virtual void bark() {}
};
class Yellowdog : public Dog
{
public:
~Yellowdog() { cout << "Yellow dog destroyed" << endl; }
};
class DogFactory
{
public:
static shared_ptr<Dog> creatYellowDog()
{
return shared_prt<Yellowdog>(new Yellowdog());
}
//...creat other dogs
};
int main()
{
shared_ptr<Dog> pd = DogFactory::creatYellowDog();
//..Do something with pd
return 0;
}
/*
NOte:
All classes in STL have no virtual destructor,so be careful inheriting from them.
so you can shared_ptr when you use STL
*/