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;
But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Constructor Overriding is never possible in Java. This is because, Constructor looks like a method but name should be as class name and no return value. Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding.
Constructors are not inherited. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.
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 inherited
in a class constructor or class destructor. As David's answer points out, though, the compiler ignores calls to inherited
because 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With