Without virtual, you get:
Animal Animal
| |
dog cat
\ /
dogcat ← two copies of Animal → ambiguous speak()
With virtual:
Animal ← only one shared copy
/ \
dog cat
\ /
dogcat ← speak() is unambiguous
// Online C++ compiler to run C++ program online
#include <iostream>
class Animal{
public:
void speak(){
std::cout<<"hello"<<std::endl;
}
};
class dog: virtual public Animal{
};
class cat: virtual public Animal{
};
class dogcat: public dog, public cat{
};
int main() {
dogcat a;
a.speak();
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: