Multiple inheritance and diamond problem

5

What is the diamond problem? How do languages treat you? And they treat differently because there is such a difference?

    
asked by anonymous 31.08.2017 / 15:12

1 answer

4

If a class inherits two classes (concrete implementations), implementations conflict.

Example:

class ClasseBase1 
{
    public void Foo()
    {
        Console.WriteLine("ClasseBase1");
    }
}

class ClasseBase2 
{
    public void Foo()
    {
        Console.WriteLine("ClasseBase2");
    }
}

class ClasseDerivada : ClasseBase1, ClasseBase2
{
}

The ClasseDerivada class inherits two implementations of the Foo method, which causes a conflict because the compiler does not know which method to use.

In C # multiple class inheritance is forbidden, to avoid this diamond problem.

Multiple inheritance of interfaces is now allowed because interfaces are not implementations. The following code is valid.

Example:

interface IFoo1 
{
    public void Foo();
}

interface IFoo2
{
    public void Foo();
}

class ClasseDerivada : IFoo1, IFoo2
{
}
    
31.08.2017 / 15:19