Virtual method call from constructor

Steven Schveighoffer schveiguy at gmail.com
Wed Apr 5 13:09:54 UTC 2023


On 4/4/23 3:08 AM, Chris Katko wrote:
> Second, could you give me some case examples where this problem occurs? 
> Is the issue if I override refresh in a derived class, and the base 
> class will accidentally use child.refresh()?
> 

An example of a problem:

```d
class Base
{
    this() { virtualCall(); }
    void virtualCall() {}
}

class Derived : Base
{
    int *data;
    this() { data = new int; }
    override void virtualCall() { *data = 5; }
}
```

A derived class constructor without an explicit `super()` call, is 
injected with a `super()` call at the beginning of the constructor.

So in this case, the `Base` constructor runs before the `Derived` 
constructor. The `Base` ctor calls `virtualCall` before `Derived` is 
ready for it.

To fix this, you can explicitly call `super()` after initializing the data:

```d
this() {data = new int; super(); }
```

So there are ways to do this in a reasonable way, but that is why the 
warning exists.

-Steve


More information about the Digitalmars-d-learn mailing list