Constructor inheritance? Why not?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sun Jun 7 23:35:30 PDT 2015


On Monday, 8 June 2015 at 06:04:23 UTC, Tofu Ninja wrote:
> No its definitely not something that alot of people seem to 
> care about, but I always found it odd that constructors get 
> certain special casing like this.

I expect that it originally comes down to the fact that 
constructors aren't polymorphic and _can't_ be polymorphic. When 
you override a function, you're overriding the one in the base 
class and replacing its implementation. You can choose to call 
the base class' version of the function, but you don't have to. 
You're dynamically replacing a function.

Constructors, on the other hand, do _not_ override. A constructor 
must exist in _every_ class in the inheritance tree, and they all 
have to be called - and called in the right order. When you 
"inherit" a constructor, you're not overriding the one in the 
base class. You _still_ have to have constructors in both the 
base class and derived class. You're just telling the compiler to 
insert a constructor into the derived class which has exactly the 
same parameters as one in the base class and which simply 
forwards its arguments to the base class' constructor. There's no 
polymorphism involved at all. It's simply syntactic sugar to 
avoid having to type out the whole constructor implementation 
yourself. There's nothing dynamic about it all. Inherited 
constructors are truly just syntactic sugar. So, while they may 
be useful (as syntactic sugar often is), they add _zero_ 
functionality, unlike virtual functions.

So, yes, constructors _are_ fundamentally different from other 
functions. And the inheritance that you get with constructors is 
not at all what you get when you override a function. They're at 
most superficially similar. And older languages such as C++98 and 
Java don't have inherited constructors. They're a relatively new 
idea. So, if anything, it would be surprising if D had them. 
Constructors are just different beasts from other functions (the 
same goes for destructors). And while D has lots of new ideas in 
it, it's not like we have all of the cool, new language ideas out 
there. Maybe we'll get constructor inheritance someday, but no 
one has cared enough to add it thus far.

- Jonathan M Davis


More information about the Digitalmars-d mailing list