Writing code in a class that is dependent on the inheriting class?

So let’s say I have a class named Pocketmonster used solely for inheritance purposes. Inheriting from that class is classes Turtle, Cat, and Fish. In the Pocketmonster class, I have the code in Update below:

if (ChargedUp)
{
UseAbility();
}

But the method UseAbility is only going to be defined once I define it in the inheriting classes because UseAbility is dependent on what creature it is, yet I’d still like it to be called in the Pocketmonster class because having an ability is common among anything that inherits from the Pocketmonster class. So what is the best way to do this? Using a delegate? I’d think that there would be some official way to do this sort of thing.

Hi,

I believe in c# you would need to create the function using the virtual keyword in the base class.
This allows you to set the name, return type and arguments but not the implementation.

In the derived classes you would use the overrideto then create a unique implementation per derived class.

If you search for those terms (Virtual class, Override class) online you will find a lot of information about this.

The official C# version of this is the abstract class and abstract function.

This is the counterpart of C++ virtual functions, with a few limitations.

The idea is exactly as you’ve expressed it. A function is called in the base as a natural function of the code, but that function is abstract, unknown explicitly, in the base class, and requires that a derivative class implement that function.

Inheriting from an abstract class implies a demand upon the derivative to answer the question posed by this abstract function or functions. The compiler will insist that any derivative supply a concrete function, and the abstract base can’t be instantiated because it is abstract.

You begin in the declaration of the base class with something like:

public abstract class PocketMonster : MonoBehaviour // or whatever base, or no base at all
{
 public abstract bool ThatFunction();
}

This is an example of the required keywords which make PocketMonster an abstract class, and declares an abstract function where there is no body to the function. “ThatFunction” is now an abstract function, which can be called in any code written in PocketMonster.

In a derivative:

public class Fish : PocketMonster
{
 public override bool ThatFunction() { return true; }
}

In the derived class, use the keyword override to indicate Fish answers the required abstract function ThatFunction. In this case it is trivial, just returning true, but it can do whatever is required, including calling other functions.

Fish will be required to provide overrides for every abstract function declared in PocketMonster by the C# compiler.