Avatar ·

What is a virtual base class in C++ and why is it needed in multiple inheritance?

Hello everyone! I recently started learning C++ and encountered a problem when using multiple inheritance. I have a base class `Animal`, from which `Bird` and `Mammal` are derived. Then I want to create a class `Bat` that inherits from both `Bird` and `Mammal`. But the compiler gives an ambiguity error when I try to call the `speak()` method defined in `Animal`. Here is the example code: ```cpp class Animal { public: void speak() { cout << "Animal sound\n"; } }; class Bird : public Animal {}; class Mammal : public Animal {}; class Bat : public Bird, Mammal {}; ``` When trying to create a `Bat` object and call `bat.speak()`, I get an error. I've heard about `virtual` for base classes, but I don't understand how it works and what the difference is. Please explain what a