When you define a class constructor in a base class (i.e. to set some static class variable), is it possible to override this class constructor in a derived class and call the constructor from its hierarchal parent with inherited?
Example:
TBaseclass = class(TObject)
public
class constructor ClassCreate; virtual;
end;
TOtherClass = class(TBaseClass)
public
class constructor ClassCreate; override;
end;
**implementation**
class constructor TBaseClass.ClassCreate;
begin
//do some baseclass stuff
end;
class constructor TotherClass.ClassCreate;
begin
inherited;
//do some other stuff
end;
There is no reason for class constructors to be virtual since they cannot be invoked polymorphically. You can’t call them directly; the compiler inserts calls to them automatically based on which classes are used in a program. Virtual methods are for run-time polymorphism, but since the compiler knows exactly which class constructors it’s invoking at compile time, there is no need for dynamic dispatch on class constructors or destructors.
Virtual methods aren’t required for inheritance, however, so there should be no problem using
inheritedin a class constructor or class destructor. As David’s answer points out, though, the compiler ignores calls toinheritedbecause it’s generally unwise to initialize a class multiple times, which is what you’d be doing if you really managed to call the inherited class constructor. If there’s something you need to happen twice, you’ll need to find a different way to make it happen.