0

I am exploring diamond problem. I have written below code. However it shows ambiguous issue. How to resolve it? Is it possible without overriding method in Snake class?

    #include <iostream>
    class LivingThing {
    protected:
       void breathe()
       {
          std::cout << "I'm breathing as a living thing." << std::endl;
       }
    };

    class Animal : virtual protected LivingThing {
    protected:
       void breathe() {
          std::cout << "I'm breathing as a Animal." << std::endl;
       }
    };

    class Reptile : virtual public LivingThing {
    public:
       void breathe() {
          std::cout << "I'm breathing as a Reptile." << std::endl;
       }
    };

    class Snake : public Animal, public Reptile {

    };

    int main() {
       Snake snake;
       snake.breathe();
       getchar();
       return 0;
    }
Melon
  • 604
  • 1
  • 7
  • 30
  • 5
    i'd rather fix the hierachy, in what world an `Reptile` is not an `Animal`? Why do you have multiple inheritance in the first place? – 463035818_is_not_an_ai Apr 02 '19 at 11:12
  • Please provide the actual error message. Also, why do you use protected inheritance in `Animal`? – r3mus n0x Apr 02 '19 at 11:14
  • Have you read: https://stackoverflow.com/questions/2659116/how-does-virtual-inheritance-solve-the-diamond-multiple-inheritance-ambiguit – Melon Apr 02 '19 at 11:16

1 Answers1

3

What happens here is that Animal and Reptile both overwrite the LivingThing::breathe() method with their own version. Snake, thus, inherits two different methods, both called breathe, one from each of its base classes. When you then write

snake.breathe();

the name breathe is ambiguous because it could refer to either Animal::breathe or Reptile::breathe. You have to explicitly tell which one should be called, for example

snake.Reptile::breathe();

This is most likely not what you wanted. breathe() is not a virtual method. You most likely wanted it to be a virtual method, however, in which case you most definitely should have a look at How does virtual inheritance solve the "diamond" (multiple inheritance) ambiguity?.

Michael Kenzel
  • 15,508
  • 2
  • 30
  • 39