Abstract functions in child classes
Jacob Carlborg
doob at me.com
Thu Dec 1 23:23:02 PST 2011
On 2011-12-01 19:14, Simen Kjærås wrote:
> 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.
There's also the possibility to have the declarations in one object file
and the implementation in another, if I recall correctly. This allows to
use a .di and .d file, similar to .c and .h in C/C++.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list