Abstract functions in child classes
Simen Kjærås
simen.kjaras at gmail.com
Thu Dec 1 10:14:16 PST 2011
On Thu, 01 Dec 2011 18:50:48 +0100, Adam <Adam at anizi.com> wrote:
> Ok, starting to feel like I'm missing something obvious...
>
> The abstract keyword in the language reference states:
> "Functions declared as abstract can still have function bodies. This
> is so that even though they must be overridden, they can still
> provide �base class functionality.�"
>
> So, "they must be overridden." Does the compiler do *anything* to
> verify this for a child class?
>
> This compiles:
>
> import std.stdio;
>
> public abstract class Parent {
> public void hasDefinition() {
> writeln("I have a definition");
> }
>
> public abstract void noDefinition();
> }
>
> public class Child : Parent {
> public void unRelated() {
> writeln("Unrelated");
> }
> }
>
> void main() {
> Child child;
> }
>
> However, if I change main() to:
>
> void main() {
> Parent instance = new Child();
> }
>
> I get "cannot create instance of abstract class Child | function
> noDefinition is abstract"
>
> Why is a reference / use of child in the context of a parent
> required just to validate that the class is a valid extension of the
> parent? More to the point, why does the first case even compile?
Child is an abstract class because it has abstract methods. One of
these is the original hasDefinition, the other is noDefinition. Child
itself is under no obligation to override them, because there could be
a class GrandChild : Child, which does override them.
Declaring a variable of type Child, where Child is abstract class,
should of course not be an error. That child could be either a Son or
a Daughter (or a transvestite child, I guess, but let's not get too
carried away), both of whom override these abstract methods.
That said, it would be a lot clearer if the language gave an error
when a class with abstract methods is not marked abstract.
More information about the Digitalmars-d-learn
mailing list