Recent

Author Topic: Virtual Method  (Read 3719 times)

Medhome

  • New Member
  • *
  • Posts: 28
Virtual Method
« on: January 03, 2025, 10:16:12 am »
Hi all,

I got Runtime Error with my sample project using freepascal and concerning casting tform and using virtual method
This sample use 2 forms 1 BaseForm (TFORM) 2 TF1 (BaseForm) inherited

BaseForm has the procedure Procedure whenDeleteRec(dataset:tdataset) virtual;Abstract

TF1
Procedure whenDeletedRec(dataset:tdataset); override;

Now in the MainForm when I do baseform (p).WhenDeletedRec(dataset) where p is a pointer to tf1 I got a runtime error.

Regards Med

rvk

  • Hero Member
  • *****
  • Posts: 6684
Re: Virtual Method
« Reply #1 on: January 03, 2025, 10:26:41 am »
Now in the MainForm when I do baseform (p).WhenDeletedRec(dataset) where p is a pointer to tf1 I got a runtime error.
WHAT runtime error do you get.
ALWAYS copy and paste the exact error in your post.

And show some code how you declared and created your P variable.

Are you sure your P contains a correct initiated class (inherited from BaseForm)?

Thaddy

  • Hero Member
  • *****
  • Posts: 16652
  • Kallstadt seems a good place to evict Trump to.
Re: Virtual Method
« Reply #2 on: January 04, 2025, 09:49:45 am »
The cast to baseform may have changed to the vmt entry of baseform, not the vmt entry of the derived form.
Hence you get an abstract error. You are probably using the cast wrong.
Either that or the derived form is not created.
« Last Edit: January 04, 2025, 10:32:52 am by Thaddy »
But I am sure they don't want the Trumps back...

rvk

  • Hero Member
  • *****
  • Posts: 6684
Re: Virtual Method
« Reply #3 on: January 04, 2025, 11:41:38 am »
The cast to baseform may have changed to the vmt entry of baseform, not the vmt entry of the derived form.
More likely is that the pointer p isn't initialized.
But since we don't get information about the code and the actual error it's just guessing.

I initially thought putting a class in a classless pointer would loose some information but it doesn't. That also just works (see below).
So it's not an abstract error that's getting thrown here, is my guess. But just an access violation or something else.

Code: Pascal  [Select][+][-]
  1. program Project1;
  2.  
  3. type
  4.   TAnimal = class
  5.     procedure Sound; virtual; abstract;
  6.   end;
  7.  
  8.   TCat = class(TAnimal)
  9.     procedure Sound; override;
  10.   end;
  11.  
  12.   procedure TCat.Sound;
  13.   begin
  14.     writeln('miauw');
  15.   end;
  16.  
  17. var
  18.   animal: TAnimal; // notice the variable is even base class
  19.   p: pointer;
  20. begin
  21.   animal := TCat.Create; // but we create it as child class
  22.   p := animal;
  23.   TAnimal(p).Sound;  // shows miauw
  24.   readln;
  25. end.
  26.  

 

TinyPortal © 2005-2018