William Goddard William Goddard - 4 years ago 261
Pascal Question

Pascal Access Violation when calling a variable in a class

I have made some very simple code in Pascal that is getting me this error:


Project BugFixing.exe raised exception class EAccessViolation with message 'Access violation at address 0040F1EE in module 'BugFixing.exe'. Write of address 00000004'.


The program consists of 2 modules:
BugFixing.dpr:

program BugFixing;

{$APPTYPE CONSOLE}

uses
SysUtils, uLinearProgrammingMainLogic in 'uLinearProgrammingMainLogic.pas', math;

var
MinOrMax : integer ;
Question : TQuestion ;

begin
try
Randomize ;
MinOrMax := RandomRange(0,2) ;
Question.SetMaximiseQuestion(MinOrMax);

except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.


And uLinearProgrammingMainLogic.pas:

unit uLinearProgrammingMainLogic;

interface

uses sysUtils, math ;

type

TQuestion = class
private
MaximiseQuestion : boolean ;
public
procedure SetMaximiseQuestion (MinOrMax : integer) ;
end;

implementation

procedure TQuestion.SetMaximiseQuestion(MinOrMax : integer);
begin
if MinOrMax = 0 then
MaximiseQuestion := true
else
MaximiseQuestion := false ;
end;

end.


If anyone could explain to me why this is creating an access violation, that'd be appreciated. Thanks in advance. :)

Answer Source

A class must always be instantiated (TClassType.create) before use. The only exception to that are class/static methods, but you don't declare them that way (and that is not basic usage anyway)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download