Why is the constructor of B called?

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 23 15:35:31 PDT 2015


On Wed, Sep 23, 2015 at 03:25:04PM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
> On 09/23/2015 02:25 PM, 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?
> 
> No and I don't think it will ever be implemented. The derived class is
> supposed to be used as the super class, which involves proper
> construction of the super parts.
[...]

I can't think of any valid use case for not running the base class ctor.
Are you sure you aren't violating the Liskov Substitution Principle in
some way?  It may be that what you need is a has-a relationship rather
than an is-a relationship in your class.


T

-- 
Once the bikeshed is up for painting, the rainbow won't suffice. -- Andrei Alexandrescu


More information about the Digitalmars-d-learn mailing list