Can you override the class constructor and use inherited ones?

When you define a class constructor in a base class (i.e., set some static class variable), is it possible to override this class constructor in a derived class and call the constructor from its hierarchical parent with the 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; 
+7
source share
2 answers

There is no reason for class constructors to be virtual, because they cannot be called polymorphically. You cannot call them directly; the compiler automatically inserts calls to them based on which classes are used in the program. Virtual methods are designed for run-time polymorphism, but since the compiler knows exactly which class constructors it invokes at compile time, there is no need to dynamically send it to class constructors or destructors.

Virtual methods are not required for inheritance, so there should be no problem using inherited in a class constructor or class destructor. As David's answer indicates, the compiler ignores calls to inherited because it is usually not wise to initialize the class several times, which was what you do if you really managed to call the inherited constructor class. If you need to repeat something twice, you need to find another way to do it.

+16
source

For starters, since class constructors cannot be virtual (it makes no sense to be virtual), you need to remove the virtual and override keywords in order to compile your code.

Class constructors are commonly used to initialize vars classes. Classes of classes usually should be initialized once and once. If you could call inherited as you suggest in the question, then TBaseClass.ClassCreate will be called several times when in fact it needs to be called exactly once.

While you can write inherited in the constructor of the class and the code will compile, the compiler simply ignores it.

 program ClassConstructors; {$APPTYPE CONSOLE} uses SysUtils; var Count: Integer; type TBaseclass = class public class constructor ClassCreate; end; TOtherClass = class(TBaseClass) public class constructor ClassCreate; end; class constructor TBaseClass.ClassCreate; begin inc(Count); end; class constructor TotherClass.ClassCreate; begin inherited; end; begin TBaseClass.Create.Free; TOtherClass.Create.Free; Writeln(Count);//outputs 1 Readln; end. 

Note that, of course, both class constructors are executed.

+9
source

All Articles