Why are virtual functions needed in C++? Explain with an example
Hi! I've just started learning C++ and I'm trying to understand virtual functions. I've read many articles, but I still don't fully understand why they are needed.\n\nI have a base class `Animal` and derived classes `Dog` and `Cat`. I want each animal to have its own sound. Without virtual functions, I wrote this:\n\n```cpp\nclass Animal {\npublic:\n void speak() { cout << "Some animal sound"; }\n};\nclass Dog : public Animal {\npublic:\n void speak() { cout << "Woof!"; }\n};\nclass Cat : public Animal {\npublic:\n void speak() { cout << "Meow!"; }\n};\n```\n\nWhen I create objects directly, everything works:\n\n```cpp\nDog dog;\nCat cat;\ndog.speak(); // Woof!\ncat.speak(); // Meow!\n```\n\nBut if I use a pointer to the base class, the base class method is called,
No answers yet.
Log in to leave an answer
Blogs
Algorithms and Data Structures in PHP: A Practical Guide for Web Developers
Generics in C#: Why They Are Needed and How to Use Them in Practice
Functional Programming in Kotlin: Advanced Techniques and Practices
Most Effective Python Learning Path: Complete Guide