Miguel Moura
Miguel Moura

Reputation: 39364

Derived Class Method hides inherited member

I have a base class and two derived classes:

public abstract class BaseClass {

    public IEnumerable<Double> Inputs { get; protected set; }

    public BaseClass(IEnumerable<Double> inputs) {

        foreach (Double input in inputs)
            Compute(input);
    } 

    protected abstract Double Compute(Double input);
}

public abstract class DerivedClass1 : BaseClass {

    protected abstract Double Compute(Double input);
}

public class DerivedClass2 : DerivedClass1 {

    private override Double Compute(Double input) {

    // Compute implementation

    }
}

I get the error on DerivedClass1 Compute method:

'DerivedClass1.Compute(Double)' hides inherited member 'BaseClass.Compute(Double)'. To make the current member override that implementation, add the override keyword.

How to solve this?

Upvotes: 0

Views: 381

Answers (2)

Christopher
Christopher

Reputation: 9804

There are two things that can happen with Functions when you inherit classes: Overriding and Hiding.

Hiding is the kind of thing that was invented very early on when thinking up the idea of OOP. So everyone implements. I can not remember having ever used, seen someone use or even seriously thinking about using it in code. The main reason to know about it, is to not accidentally do it instead of overriding.

Overriding is the way more usefull thing. You use it 99.999% of all cases. The only downside is that the option of overriding has to be enabeled and maintained every step of the inheritance chain that implements the function. If I run into a case where I can not override, there is only one Option: Just encapsulating this in another class that I can override.

I am very surprised that hiding has been classes as a Compiler error. However I am also getting 4 other errors in that code. Mostly stuff about the accessors not matching overriding/hiding behavior (it must be at least protected and you can not change acessibility afterwards). So it might well be a case where parsing is so tripped up, it starts inventing problems that do not mater.

As long as a class is abstract, you do not need to code out anything. Abstract classes are there to get "step" in the class heirarchy. I have seen abstract classes used for collecting Interfaces and nothing more. The actuall implementation was still 100% the inheritors job. Coding stuff out is entirely optional - not having to code out stuff is usually the goal.

Upvotes: 0

BartoszKP
BartoszKP

Reputation: 35891

You don't need to redeclare this method as abstract again, just remove it:

public abstract class DerivedClass1 : BaseClass {
}

You will need to provide a constructor though, because BaseClass doesn't have a default constructor and requires an argument to be instantiated.

Upvotes: 7

Related Questions