using namespace available outisde namespace

A

Andrew Ward

Hi,
The following code compiles fine for me, however I would have thought it
should return an error at least in foo(). Is there a good reason why the
using namespace N1; continues past the end of namespace N2?

namespace N1
{
class C1
{
public:
void f1() {}
};
}

namespace N2
{
using namespace N1;
class C2
{
C1 c;
void f2();
};
}

void N2::C2::f2()
{
C1 c;
c.f1();
}

void foo()
{
C1 c;
c.f1();
}
 
V

vindhya

using namespace N1;

Because of this line. The scope of this doesnt ends and therefore you
are able to access C1 methods in void foo()
 
A

Andrew Ward

vindhya said:
using namespace N1;

Because of this line. The scope of this doesnt ends and therefore you
are able to access C1 methods in void foo()

I can see that is the way it works, though I was wondering if there is a
good reason for it to work this way. It seems like it would be better
for the 'using namespace N1' to finish at the end of the scope. Then you
could use this technique in header files so you don't have to keep on
typing N1::
 
V

vindhya

In fact I was working with std namepace where I found that if I write
"using namespace std" in one header it was borrowed in almost 70% of
codes. So its better to use namespace A { } in the cases where there
may be any chances of ambiguity. In fact ISO standard also defines this
ambiguity.
 
A

Alan Johnson

Andrew said:
Hi,
The following code compiles fine for me, however I would have thought it
should return an error at least in foo(). Is there a good reason why the
using namespace N1; continues past the end of namespace N2?

namespace N1
{
class C1
{
public:
void f1() {}
};
}

namespace N2
{
using namespace N1;
class C2
{
C1 c;
void f2();
};
}

void N2::C2::f2()
{
C1 c;
c.f1();
}

void foo()
{
C1 c;
c.f1();
}

The way I read the standard, the use of C1 in foo() is in fact an error.
For reference, g++ 4.0 (and maybe earlier versions, I haven't checked)
does consider it an error.

-Alan
 
A

Andrew Ward

Alan said:
The way I read the standard, the use of C1 in foo() is in fact an error.
For reference, g++ 4.0 (and maybe earlier versions, I haven't checked)
does consider it an error.

-Alan

Well that would be nice to have, if only I didn't have to use VC7.1
I might ask the people over at ms.public.vc.language what the behaviour
is in VC8.0

Andrew.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top