Search code examples
delphidelphi-7

Inaccessible value causing Access violation


I have a program that makes a bike (TObject)

When calling my Create method, I get an access violation error 00453359 and a write of address 00000004.

constructor MyBike.Create(iPrice, iStroke, iYear, iCC: Integer; sName,
  sModel: string);
begin
  fCC := iCC; // <- Here is the error
  fPrice := iPrice;
  fStroke := iStroke;
  fYear := iYear;
  fName := sName;
  fModel := sModel; 

When I watch that line, it says that it is an inaccessible value, as for all the variables there.

Here is the rest of my class:

type
  MyBike = class(TObject)
  private
    fCC, fStroke, fYear, fPrice: Integer; //I will at a later stage use fPrice as a currency
    fName, fModel: string;
  public
    constructor Create(iPrice, iStroke, iYear, iCC: Integer; sName, sModel:
      string);
    function GetValues: string;
  end;

implementation

{ MyBike }

constructor MyBike.Create(iPrice, iStroke, iYear, iCC: Integer; sName,
  sModel: string);
begin
  fCC := iCC;
  fPrice := iPrice;
  fStroke := iStroke;
  fYear := iYear;
  fName := sName;
  fModel := sModel;
end;

and my main unit:

private
    { Private declarations }
    NewBike : MyBike;
  public
    { Public declarations }       
  end;

var
  Form1: TForm1;
  redtSavedObject: TRichEdit;
  btnClearSavedObject: TButton;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  btnSaveToText.Enabled := False;
  btnSavetodata.Enabled := False;
end;

procedure TForm1.btnSaveasObjectClick(Sender: TObject);
var
  Price, Year, CC, Stroke : Integer;
  Name, Model : String;

begin
  Price := StrToInt(edtPrice.Text); //All of these values are fine
  Year := StrToInt(edtYear.Text);
  CC := StrToInt(edtCC.Text);
  Stroke := StrToInt(edtStroke.Text);
  Name := edtName.Text;
  Model := edtModel.Text;

  NewBike.Create(Price, Stroke, Year, CC, Name, Model);

I looked at this post: Delphi strange inaccessible value (acess violation) o.O and says I must edit the project settings to:

Debug info: ON

Local Symbols: ON

Optimization: OFF.

Ive done a rebuild, still no change. Ive gone as far as restarting my pc to no avail


Solution

  • Change

    NewBike.Create(Price, Stroke, Year, CC, Name, Model);
    

    To

    NewBike := MyBike.Create(Price, Stroke, Year, CC, Name, Model);
    

    Thats the correct way to mane a new instance of a Class.

    When you create an new instance of a class you call then constructor on the Class (MyBike) and assign it's retun value to a variable NewBike := MyBike.Create(...);`

    Inside every object (instance of a class) you have a hidden parameter called Self more info on Delphi Basics. The problem in your case was that you didn't create a new instance of the class and therefor your self variable was nil.