954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Empty Object Variables

Basically I have a object class like this:

Type TSomething = Class
  Private
    Blah : Integer;
  Public
    Procedure DoSomething;
End;

Type TSecond = Class(TSomething)
  Public
    Procedure DoSomethingNew;
End;
Procedure TSecond.DoSomethingNew;
Begin
  ShowMessage(IntToStr(Blah));
End;


...and the code to call the classes is:

Try
  Something := TSomething.Create;
  Something.Blah := 5000;
Finally
  Something.Free;
End;

Try
  Second := TSecond.Create;
  Second.DoSomethingNew;
Finally
  Second.Free;
End;


Now even though I assign the value "5000" to the variable Blah in the main class, when I try to check the value of Blah in the second class it returns a null (0) value. Why is the variable wiped when I have assigned a value to it already.

How can I overcome this problem? I am new to object orientated programming so I'm not too sure why this isn't working, is it because I am freeing the memory? I was thinking of having one main class which has variables which all the sub-classes will use, but the main classes variables keep on getting wiped whenever I check them in sub-classes.

DelphiGuy
Light Poster
31 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

You are right. When you create a new instance of a class (with .Create), all variables (members) for that object (instance of a class) are initialized. You can give them whatever default value you want, if you use a constructor . You may want to read this .

pritaeas
Posting Expert
Moderator
5,480 posts since Jul 2006
Reputation Points: 653
Solved Threads: 874
 

Thanks! The constructor was the solution, how do I mark this as solved? Thanks again.

DelphiGuy
Light Poster
31 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You