Virtual method call from constructor
Chris Katko
ckatko at gmail.com
Tue Apr 4 07:08:52 UTC 2023
dscanner reports this as a warning:
```D
struct foo{
this()
{
/* some initial setup */
refresh();
}
void refresh() { /* setup some more stuff */}
// [warn] a virtual call inside a constructor may lead to
unexpected results in the derived classes
}
```
Firstly, are all calls virtual in a struct/class in D? Is this
any different from C++? IIRC, in C++, a struct cannot have
virtual calls, and virtual methods are explicit keywords in
classes.
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()?
Third, is there the expectation that you should _never_ call any
internal, private, methods inside a constructor? Or do I just
call/structure it a different way?
For a concrete example: I have a particle struct. It makes sense
to me, to have initial setup code (placed in the refresh()
function) called by this(), that later I can then call again; to
reset the struct to an initial state in-memory without
re-allocations.
I imagine in D that there's probably something like:
```D
particles[235] = foo.init;
```
but that blows up in a scenario where I'm only _partially_
resetting the struct data. For example, if I had a bunch of
pointers to system modules, those values don't need to be nulled
and re-set every time in this(), whereas the physical data like
position, velocity, angle, need reset in refresh(). You could
architect around that, but I'm trying to learn the language
mechanics.
More information about the Digitalmars-d-learn
mailing list