7

In C++, if I have to call a function from another namespace, say foo, I have two options: adding the using namespace foo; above my code or specifying the namespace when I perform the call, that is foo::myFunction().

In Delphi, is there a construct corresponding to the second alternative?

2
  • I don't see how your C++ scenarios have anything to do with the title. How are they related to using units in Delphi? They involve the same base word use, but that's about it. Jul 16, 2013 at 17:15
  • 2
    @RobKennedy: Pascal's units behave much like namespaces of just one code file. So, the scenarios are an valid metaphor from an C++ POV. Jul 16, 2013 at 20:24

1 Answer 1

10

No, there isn't. If an identifier (such as a function, like myFunction) is declared in unit foo, then in a different unit, bar, say, you cannot use myFunction without adding foo to the uses clause either in the implemantation or in the interface section.

Some discussion

Let's say that you have two functions MyFunc, one in foo and one in bar. Let's say you're in foo. If you don't add bar to one of the uses lists, then MyFunc will refer to foo.MyFunc, and you cannot access the other function. If you add bar to one of the uses lists, then MyFunc will still refer to the local function foo.MyFunc, but you can access the other by writing bar.MyFunc. To reduce the risk of confusion, you could choose always to be explicit and write foo.MyFunc and bar.MyFunc, and never only MyFunc.

A common scenario is this: you got an identifier ident in both foo and bar (they could be very different), and in MyUnit, you have both foo and bar in some uses list. Then, in MyUnit, ident will refer either to foo.ident or bar.ident, depending on which unit comes last in the uses clauses. To use the other one, you have to be explicit about the unit (like foo.ident or bar.ident). Of course, to reduce the risk of making mistakes, you could always be explicit (e.g. write foo.ident even if foo comes last, so that ident also refers to foo.ident).

A common mistake is to confuse Windows.TBitmap with Graphics.TBitmap. Normally, TBitmap refers to Graphics.TBitmap (the Windows unit usually comes early in uses clauses). This confusion has been treated at SO.

2
  • Ok thanks, so if I have a procedure with the same name both in unit foo and in unit bar, I am screwed?
    – Paolo M
    Jul 16, 2013 at 15:55
  • Ahem, you seem to take topicstarter's "first" and "second" alternative in wrong order Jul 16, 2013 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.