Why are virtual functions needed in C++? Explain with an example
Hello, colleagues! I've just started learning C++ and I can't understand the purpose of virtual functions. I've read many articles, but it's still a mess in my head.
For example, I have a base class Animal and two derived classes Dog and Cat. I want each animal to have its own sound. Here's how I did it without virtual functions:
```cpp
#include
#include
class Animal {
public:
void speak() { std::cout << "Some generic animal sound\n"; }
};
class Dog : public Animal {
public:
void speak() { std::cout << "Woof!\n"; }
};
class Cat : public Animal {
public:
void speak() { std::cout << "Meow!\n"; }
};
int main() {
std::vector zoo;
zoo.push_back(new Dog());
zoo.push_back(new Cat());
for (auto animal : zoo) {
No answers yet.
Log in to leave an answer
Blogs