On Friday, 4 January 2019 at 09:19:48 UTC, Simen Kjærås wrote:
On Friday, 4 January 2019 at 08:40:04 UTC, Alex wrote:
class A
{
public:
    int foo(){return 1;}
};
class B : public A
{
public:
    int foo(){return 2;}
};

In C++, methods are non-virtual by default. In D, they are virtual by default. Because of this, the two examples are different. In fact, D disallows overriding non-virtual, non-private functions, as specified in https://dlang.org/spec/function.html#virtual-functions. For private functions it does work, though:


Ha... got it!
Because final methods are allowed in interfaces, maybe this is the answer to the OP...

class A {
    private final int foo() { return 1; }
}
class B : A {
    final int foo() { return 2; }
}

unittest {
    assert((new A).foo == 1);
    assert((new B).foo == 2);
    assert((cast(A)(new B)).foo == 1);
}

Imagine you give me a box with an Animal in it. You know it's a Bird, but I only know it's an Animal of some kind.

Case 1: I tell it to move() to the top of a tree. Would you expect it to climb or fly? (let's not get into penguins and other flightless birds right now, the OOP animal metaphor is strained enough as it is)

Case 1 is overriding - Bird has defined how move() should work, and it will do that even if you only know it's an animal of some kind.

This can be exemplified in D as:

import std.stdio : writeln;

abstract class Animal {
    abstract void move();
}

class Bird : Animal {
    override void move() {
        writeln("Flying.");
    }
}


unittest {
    (new Bird).move(); // Flying
    (cast(Animal)new Bird).move(); // Flying
}

--
  Simen

Case 2 is clear. I was wondering about the behavior in case 1: not because of the override behavior, but because there is an explicit cast in between. I assume the move method of an Animal is not abstract, and therefore I supposed, casting to this type explicitly should restore this very non-abstract behavior. But this is not the case. And the final/virtual thing above explains this to some extent, too... I think...

Reply via email to