Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Constructor, Create and Access Violation, why? 1

Status
Not open for further replies.

ddverne

Programmer
Dec 29, 2011
9
BR
Hi,

I created the following class:

type
TDBConector = class(TCustomClientDataSet)
Conn : TADOConnection;
private
DBConfig : TDBConfig;
public
constructor Create(Aowner : TComponent); overload;
end;

And the constructor where the error occurs, in fact the error occurs on the assignment of the ConnectionString := '';

constructor TDBConector.Create(Aowner : TComponent);
begin
inherited Create(Aowner);

with Conn do
begin
Active := False;
ConnectionString := '';
try
Connected;
except
on E : Exception do
begin
ShowMessage('Error: '+E.message);
end;
end;
end;
end;

If I put this line before use Conn :

"Conn := TADOConnection.Create(Self);"

It works perfectly, but that makes me think, 'conn' shouldn't be created automatically?

So, I need to do that for every class that I declare like that before use?

Finally, If I'll need do what I said above, I'll need free them all on the destructor too, right?

Thanks.
 
Nope. All Dynamic variables inside of a class must be created inside of the constructor; that is the primary purpose of the constructor. All VCL components in Delphi are dynamic variables, which means, you must create all VCL members of the class in the constructor. Therefore you must create Conn before accessing it, even inside the constructor (and delete them in the destructor, too).
 
Prattaratt,

I understood.

Thank you very much.
 
Adding to Prattaratt's answer:

general way to use objects:

Code:
procedure UseAndObject;

var Object : TMyObject;

begin
 Object := TMyObject;
 try
  Object.Field := 'Avalue';
  DoSomethingWithMyObject(Object);
 finally
  FreeAndNil(Object);
 end;
end;
If you need the object within a larger scope (for example as a variable of a TForm) the correct places the create/destroy object would be formcreate and formdestroy

/Daddy

-----------------------------------------------------
What You See Is What You Get
Never underestimate tha powah of tha google!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top