[fpc-pascal] Re: Interesting namespace question

L L at z505.com
Mon Jun 25 00:27:14 CEST 2007

Ido wrote:
> I saw an interesting bug on C++, and I was wondering how to solve this
> type of bug in Pascal:
> program namespace_test;
> function test : boolean;
> begin
>  result := true;
> end;
> type
>  TTest = class
>     function test : boolean;
>  end;
> function TTest.test : boolean;
> begin
>  result := test;
> end;
> var
>  c_test : TTest;
> begin
>  c_test := TTest.create;
>  try
>    writeln (c_test.test);
>  finally
>    c_test.free;
>  end;
> end.
> OK the question is, the TTest.test, what is the test function that it
> will call, the one inside the class, or the one outside it (I belive
> that it will call itself once), and how can i call the function
> outside the class ?

The code should be put into a Unit instead.

Even inside UnitOne you can still reference Unit 1 "SELF" by going unit1.test.

A program doesn't have a namespace that one can access, AFAIK (someone care
to correct?).

Shoving algorithms into a program rather than placing them in units leads to
global C-like or old standard pascal like code where there are no units, just
all one big monolithic collosal program melted together with include
files or jammed into one big source file.

The other option would be to put the Test function inside a Record and access
the test function through the record, treating the record as a namespace. The
record would have to be initialized:

TNameSpace = record
  test: function:boolean;

function test: boolean;
  result:= true;

var  // initialized record
  NameSpace: TNameSpace(test: @test);


More information about the fpc-pascal mailing list