My descendant constructor skipped an important appointment

Go down

My descendant constructor skipped an important appointment

· #1

I made a base class that creates a string list, then a descendant that adds its first entry. The descendant's constructor does not call inherited Create. Accessing the list fails.

I thought the language automatically ran every constructor on the way down. Is the instance itself missing, or only the list?

Re: My descendant constructor skipped an important appointment

· #2

The descendant instance has been allocated. Your ancestor's constructor body has not run, so its list field is still nil.

Calling inherited Create runs the ancestor initialization on the same instance. It does not allocate a second base object.

Here is a complete corrected console example:

pascal
program ChecklistDemo;
{$mode objfpc}{$H+}
uses
  Classes;
type
  TNotebook = class
  protected
    FLines: TStringList;
  public
    constructor Create;
    destructor Destroy; override;
    function Count: Integer;
  end;

  TChecklist = class(TNotebook)
  public
    constructor Create;
  end;

constructor TNotebook.Create;
begin
  inherited Create;
  FLines := TStringList.Create;
end;

destructor TNotebook.Destroy;
begin
  FLines.Free;
  inherited Destroy;
end;

function TNotebook.Count: Integer;
begin
  Result := FLines.Count;
end;

constructor TChecklist.Create;
begin
  inherited Create;
  FLines.Add('Call the ancestor constructor');
end;

var
  Notes: TChecklist;
begin
  Notes := TChecklist.Create;
  try
    WriteLn(Notes.Count);
  finally
    Notes.Free;
  end;
end.

The output is 1. The destructor releases the list before calling the inherited destructor.

Re: My descendant constructor skipped an important appointment

· #3

That fixes it. I was confusing allocating the instance with initializing everything it owns.

I appreciate that the first checklist item is also the repair.

Re: My descendant constructor skipped an important appointment

· #4

I once removed an inherited constructor call because it appeared to do nothing. It created the lock used by the next method.

The optimization removed one call and the rest of the afternoon.

Re: My descendant constructor skipped an important appointment

· #5

DOES EVERY CONSTRUCTOR NEED THE SAME ARGUMENTS AS ITS PARENT?

sorry. also, actual question.

SORRY ABOUT THE CAPS

Re: My descendant constructor skipped an important appointment

· #6

No. A descendant can declare a different constructor signature. Its implementation must pass appropriate arguments to whichever ancestor constructor it calls. For a component constructor that receives an owner, the usual pattern passes that owner to the inherited constructor.

The ancestor's required initialization still matters even when the signatures differ.

Read the error message. Then read it again.

Go up

Sign in to reply