Home > Mobile >  Members that are only accessible to child class if child class override them?
Members that are only accessible to child class if child class override them?

Time:03-21

I'm trying to make a base class that has variables that must be overridden if they're going to be used by the child class, but if they're not overridden they can not be accessed by the child class.

Is that possible?

CodePudding user response:

No, nothing like that exists in the language, at least with all the requirements you're looking for.

This explanation also assumes that "child class" is not abstract.

...a base class that has variables that must be overridden...

That's what abstract is for. This keyword means you must override the member in a child class. You must also ensure that your base class is abstract as well (IE, you can't directly construct the base class, only indirectly through the child class).

...if they're going to be used by the child class...

There's no way to conditionally enforce if a member should be overridden or not. If you apply abstract, it must be overridden in the child class.

There's also no way to opt-out of overriding an abstract member from the child class. A child class must override all abstract members from its base class.

...but if they're not overridden...

That's what virtual is for. Virtual means that you can override a member in a child class, but if you don't then the base class's implementation holds.

...they can not be accessed by the child class...

Again, this doesn't make a lot of sense. You can mark a member as (as a simplified list) private or public (yes there are more). Private members can't be accessed by anyone but the base class, including child classes, but that also means you don't have the option for child classes to override them.

So you can't prevent a child class from accessing a base member that you're allowing it to override. abstract and virtual members cannot be private.

CodePudding user response:

by using the abstract keyword yes

information from Steve's comment

  •  Tags:  
  • c#
  • Related