Q: What happens if you don't declare an ancestor for your class and don't perform a "inherited" in the Create?

Q: What happens if you don't declare an ancestor for your class and don't perform a "inherited" in the Create?

I was going through some code to find a bug and I noticed that I have a class defined as below; with no ancestor or inherited. 

TMyClass = class
private
   constructor Create();
public

constructor TMyClass.Create();
begin
   // * THIS ISN'T HERE inherited Create();
   DoStuff();
end;


5 years ago, people said it's not a problem. 

http://stackoverflow.com/questions/772336/using-inherited-in-the-create-constructor-of-an-tobject
http://stackoverflow.com/questions/772336/using-inherited-in-the-create-constructor-of-an-tobject

Comments

  1. It's reproducable, Stefan Glienke. 

    The code reads in about a million lines of text, and splits into thread segments.

    TLogLine inherits from TObject and has no constructor.

    The class TThreadLog has a constructor  
      TThreadLog = class(TObjectList)
      public
        constructor Create;

    TThreadLogList = class(TObjectList)

    So a list of lists.  The TThreadLogList instance has OwnsObjects set true by constructor argument.

    constructor TThreadLog.Create;
    begin
      Inherited;
      OwnsObjects := True;

    gives no exception.  If I comment out inherited, I get the following crash stack and 
    a nil reference AV, when I free the TThreadLogList.

    Generics.Collections}TList.DeleteRange   
    Generics.Collections}TList.SetCount      
    Generics.Collections}TList.SetCapacity   
    Generics.Collections}TList.Destroy       
    Free                                                                   
    Generics.Collections}TObjectList.Notify
    Generics.Collections}TList.DeleteRange 
    Generics.Collections}TList.SetCount    
    Generics.Collections}TList.SetCapacity 
    Generics.Collections}TList.Destroy     
    Free

    ReplyDelete
  2. Lars Fosdal LOL, someone is losing track of his code, eh?

    Your TThreadLog inherits from TObjectList so of course you have to call that constructor because that one will call TList.Create which assigns the FComparer....

    ReplyDelete
  3. Yeah... I can't have been thinking straight in that other comment... my bad.

    ReplyDelete

Post a Comment