Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you override a class constructor and use inherited?

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;
like image 339
Bascy Avatar asked Jun 18 '12 14:06

Bascy


People also ask

Is it possible to override the constructors of a class?

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.

Can a class constructor be inherited?

Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Why constructor overriding is not possible?

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.

What happens to constructor in inheritance?

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.


1 Answers

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.

like image 75
Rob Kennedy Avatar answered Oct 18 '22 20:10

Rob Kennedy