First of all, as @Cosmin explains in some detail, the question does not concern overridden methods. The question is about calling inherited methods.
inherited Create;
is the best you can do here. This calls the TDictionary<TKey,TValue>
constructor passing the default ACapacity
of 0
.
In fact it may even be preferable to write:
inherited Create(0);
and be quite explicit.
My assumption is that your code looks like this:
type
TMyClass<TKey,TValue> = class(TDictionary<TKey,TValue>)
public
constructor Create;
end;
constructor TMyClass<K,V>.Create;
begin
inherited;
end;
I read the documentation for the inherited keyword in an attempt to understand the difference between inherited
and inherited Create
. The best clues are contained in the following excerpts:
If inherited is followed by the name of a member, it represents a normal method call ...
and
When inherited has no identifier after it, it refers to the inherited method with the same name as the enclosing method. In this case, inherited takes no explicit parameters, but passes to the inherited method the same parameters with which the enclosing method was called.
This seems to hint that the two competing uses of inherited
are treated differently.
My understanding is that inherited
results in a call to a constructor with matching parameters. In your case, TMyClass<K,V>.Create
is parameterless and so the only matching constructor is that of TObject
. Note that none of the constructors of TDictionary
can match since they all take parameters.
On the other hand, when you write inherited Create
this is a normal method call. And so default parameters can be added to the method call. The crucial point is that this variant allows calling inherited methods with non-matching parameter lists.
In my view, the inherited
syntax with no following identifier should have been reserved for virtual methods.
The designers of TDictionary<TKey,TValue>
could have saved you from this unhappy fate. The constructors of TDictionary<TKey,TValue>
should have been implemented like this:
constructor Create; overload;
constructor Create(ACapacity: Integer); overload;
.....other constructors omitted
Then the implementation for the parameterless constructor would simply be:
constructor TDictionary<TKey,TValue>.Create;
begin
Create(0);
end;
Had this decision been taken, the parameterless constructor declared in TObject
would have been hidden from any derived classes and your code would work as you intended.
The problem you have encountered here is the result of an unhappy confluence of events involving overloading, default parameters, the parameterless constructor of TObject
and the quirky syntax of inherited
for constructors. Whilst writing inherited
is highly readable and concise, it simply leads to confusion when overloaded methods are in play.
Create
. – David Heffernan