Basic class with "private" variables.

Hi.

I've created a class for use in an application and I'm having problems understanding the point of the word "private", as it seems to make no difference.

For example, here's a small class that shows my problem...

type
  TTestClass = class
    private
      _Name : String;
      procedure SetName(Value: String);
    public
      property Name : String read _Name write SetName;
    end;

procedure TTestClass.SetName(Value: String);
begin
  _Name := Value;
end;


if I create an instance of that class, then I would not expect to be able to do the following...

  oTestClass := TTestClass.Create;
  oTestClass._Name := 'Bob';

...but I can.

Can someone PLEASE tell me what the point of the "private" keyword is, AND how do I make a truly private variable that is for internal use within the class only?

Thanks in advance,

John.

PS. It's lots of points cos I need a quick answer.
LVL 6
JaymolAsked:
Who is Participating?
 
atul_parmarConnect With a Mentor Commented:
Try to do the same in another unit.

oTestClass := TTestClass.Create;
oTestClass._Name := 'Bob'; // >>> here you will get an error
0
 
atul_parmarCommented:
the scope of private is upto unit level not class level.
0
 
JaymolAuthor Commented:
Okay, I see that now.

Is there simply no way to make private declarations actually private within the same unit then?

John.
0
 
atul_parmarCommented:
NO Not in Delphi 1-7. However, in Delphi 2005/2006 there is strict private what could make it. e.g.
...
strict private
  _Name : String;
...
0
 
JaymolAuthor Commented:
Ah well.

Guess I'll just have to bear that in mind for the future.  I assumed that the variables weren't actually private, but will just stick things in separate units from now on.

Thanks for the help.
0
All Courses

From novice to tech pro — start learning today.