When should virtual destructors be used in C++?
Hello everyone! I'm a beginner C++ developer, and I'm struggling with one question. I've just started learning about polymorphism and inheritance, and I came across this situation.
Let's say I have a base class `Animal` and a derived class `Dog`. I want to use smart pointers (shared_ptr) for automatic memory management. The code looks like this:
```cpp
#include
#include
class Animal {
public:
Animal() { std::cout << "Animal created\n"; }
~Animal() { std::cout << "Animal destroyed\n"; }
virtual void speak() { std::cout << "Animal sound\n"; }
};
class Dog : public Animal {
public:
Dog() { std::cout << "Dog created\n"; }
~Dog() { std::cout << "Dog destroyed\n"; }
void speak() override { std::cout << "Woof!\n"; }
};
int main(
No answers yet.
Log in to leave an answer
Blogs