Why is the constructor of B called?
Artur Skawina via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Sep 24 06:20:41 PDT 2015
On 09/24/15 13:26, Marc Schütz via Digitalmars-d-learn wrote:
> On Thursday, 24 September 2015 at 01:01:09 UTC, Nicholas Wilson wrote:
>> On Wednesday, 23 September 2015 at 21:25:15 UTC, tcak wrote:
>>> On Wednesday, 23 September 2015 at 21:14:17 UTC, Adam D. Ruppe wrote:
>>>> On Wednesday, 23 September 2015 at 21:08:37 UTC, tcak wrote:
>>>>> I wouldn't expect B's constructor to be called at all unless "super" is used there.
>>>>
>>>> "If no call to constructors via this or super appear in a constructor, and the base class has a constructor, a call to super() is inserted at the beginning of the constructor. "
>>>>
>>>>
>>>> from http://dlang.org/class.html#constructors
>>>>
>>>> the idea is to make sure the base class construction work is done too.
>>>
>>> Is there any way to prevent this behaviour?
>>>
>>> Quickly checked whether Java acts in the same way. Answer is yes.
>>
>> You might be able to swap out the vtbl entry for a stub call it and trick the compiler and swap it back, but...
>
> Urgh...
>
> If you can modify the base class, and you really need it, you can check the dynamic type:
>
> class Base {
> this() {
> if(!cast(Base) this) return;
> // do the initialization
> }
> }
If you're going to do this then you can just use overloading.
That will both avoid the runtime check and require the hack
to be explicitly enabled in the derived class. IOW:
class B {
this() {
writeln("B.constructor");
foo();
}
struct SkipBCtor {}
this(SkipBCtor) {}
void foo() {
writeln("B.foo");
}
}
class D : B {
this() {
super(SkipBCtor());
writeln("D.constructor");
}
override void foo() {
writeln("D.foo overrides B.foo");
}
}
artur
More information about the Digitalmars-d-learn
mailing list