When a base class points to a derived class object and when delete gets called on pointer then only base class destructor gets called.
Solution 1:
TO overcome this issue, make base class destructor as virtual. With this change, both the derived class and base class destructor gets called.
Solutions 2 : Using Shared_ptr
class Dog {
public:
~Dog() { cout << "Dog is destroyed"; }
};
class Yellowdog : public Dog {
public:
~Yellowdog() {cout << "Yellow dog destroyed." <
};
class DogFactory {
public:
//static Dog* createYellowDog() { return (new Yellowdog()); }
static shared_ptr createYellowDog() {
return shared_ptr(new Yellowdog());
}
//Connot useful through Unique_ptr in this case
//static unique_ptr createYellowDog() {
// return unique_ptr(new Yellowdog());
//}
};
int main() {
//Dog* pd = DogFactory::createYellowDog();
shared_ptr pd = DogFactory::createYellowDog();
//unique_ptr pd = DogFactory::createYellowDog();
//delete pd;
return 0;
}
Solution 1:
TO overcome this issue, make base class destructor as virtual. With this change, both the derived class and base class destructor gets called.
Solutions 2 : Using Shared_ptr
class Dog {
public:
~Dog() { cout << "Dog is destroyed"; }
};
class Yellowdog : public Dog {
public:
~Yellowdog() {cout << "Yellow dog destroyed." <
};
class DogFactory {
public:
//static Dog* createYellowDog() { return (new Yellowdog()); }
static shared_ptr
return shared_ptr
}
//Connot useful through Unique_ptr in this case
//static unique_ptr
// return unique_ptr
//}
};
int main() {
//Dog* pd = DogFactory::createYellowDog();
shared_ptr
//unique_ptr
//delete pd;
return 0;
}
Comments
Post a Comment