Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi subclasses inheritance

Tags:

delphi

When I write a class I know that I can use the inherted keyword so I can inherit the behavior or TObject, such as:

type
 TOperation = class(TObject)
   constructor Create(dest, r1, r2: integer);
 end;

And the constructor will have an inherited Create;. Look at the following class:

type
 TAddition = class(TOperation)
   constructor Create(a1, a2: integer);
 end;

If the first line of TAddition is inherited Create; it means that I am inheriting the behavior of TOperation of course. But does this mean that I am also inheriting the behavior of TObject? (which is a superclass of TOperation).

When I inherit from the constructor of a father class (look at TAddition) I am inheriting only the behaviour, don't I? I am not initializing anything from the father class

The complete code is here:

 TOperation = class(TOBject)
  private
   dest, v1, v2: integer;
  public
   constructor Create(dest, r1, r2: integer);
   property destination: integer read dest;
   property value1: integer read v1;
   property value2: integer read v2;
 end;

 TMemoria = class(TOperation )
  private
   dest, r1: integer;
  public
   constructor Create(dest, r1: integer);
   property destination: integer read dest;
   property register1: integer read r1;
 end;

 constructor TOperation.Create(dest, r1, r2: integer);
 begin

  //inherit from TObject
  inherited Create;
  Self.r1 := r1;
  Self.r2 := r2; //so on...

 end;

constructor TMemoria.Create(dest, r1: integer);
 begin

  //inherit from TObject OR inherit from TOperation?
  inherited Create;

 end;
like image 930
Raffaele Rossi Avatar asked May 02 '26 01:05

Raffaele Rossi


1 Answers

constructor TMemoria.Create(dest, r1: integer);
begin
  inherited Create;
end;

This calls the parameterless constructor in TObject and does not call the constructor declared in the immediate ancestor. That much should be clear because no parameters are supplied.

For full details please see the documentation: http://docwiki.embarcadero.com/RADStudio/en/Methods_(Delphi)#Inherited

As a strong guiding principle you should not miss out calling inherited constructors from parent classes. Often this means that you fail to instantiate an object that is used by the parent class. I would regard the code in the question as very suspicious.

like image 82
David Heffernan Avatar answered May 05 '26 00:05

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!